| 1 | //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements semantic analysis for expressions. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "TreeTransform.h" |
| 14 | #include "clang/AST/ASTConsumer.h" |
| 15 | #include "clang/AST/ASTContext.h" |
| 16 | #include "clang/AST/ASTLambda.h" |
| 17 | #include "clang/AST/ASTMutationListener.h" |
| 18 | #include "clang/AST/CXXInheritance.h" |
| 19 | #include "clang/AST/DeclObjC.h" |
| 20 | #include "clang/AST/DeclTemplate.h" |
| 21 | #include "clang/AST/EvaluatedExprVisitor.h" |
| 22 | #include "clang/AST/Expr.h" |
| 23 | #include "clang/AST/ExprCXX.h" |
| 24 | #include "clang/AST/ExprObjC.h" |
| 25 | #include "clang/AST/ExprOpenMP.h" |
| 26 | #include "clang/AST/RecursiveASTVisitor.h" |
| 27 | #include "clang/AST/TypeLoc.h" |
| 28 | #include "clang/Basic/FixedPoint.h" |
| 29 | #include "clang/Basic/PartialDiagnostic.h" |
| 30 | #include "clang/Basic/SourceManager.h" |
| 31 | #include "clang/Basic/TargetInfo.h" |
| 32 | #include "clang/Lex/LiteralSupport.h" |
| 33 | #include "clang/Lex/Preprocessor.h" |
| 34 | #include "clang/Sema/AnalysisBasedWarnings.h" |
| 35 | #include "clang/Sema/DeclSpec.h" |
| 36 | #include "clang/Sema/DelayedDiagnostic.h" |
| 37 | #include "clang/Sema/Designator.h" |
| 38 | #include "clang/Sema/Initialization.h" |
| 39 | #include "clang/Sema/Lookup.h" |
| 40 | #include "clang/Sema/Overload.h" |
| 41 | #include "clang/Sema/ParsedTemplate.h" |
| 42 | #include "clang/Sema/Scope.h" |
| 43 | #include "clang/Sema/ScopeInfo.h" |
| 44 | #include "clang/Sema/SemaFixItUtils.h" |
| 45 | #include "clang/Sema/SemaInternal.h" |
| 46 | #include "clang/Sema/Template.h" |
| 47 | #include "llvm/Support/ConvertUTF.h" |
| 48 | using namespace clang; |
| 49 | using namespace sema; |
| 50 | |
| 51 | /// Determine whether the use of this declaration is valid, without |
| 52 | /// emitting diagnostics. |
| 53 | bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { |
| 54 | // See if this is an auto-typed variable whose initializer we are parsing. |
| 55 | if (ParsingInitForAutoVars.count(D)) |
| 56 | return false; |
| 57 | |
| 58 | // See if this is a deleted function. |
| 59 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 60 | if (FD->isDeleted()) |
| 61 | return false; |
| 62 | |
| 63 | // If the function has a deduced return type, and we can't deduce it, |
| 64 | // then we can't use it either. |
| 65 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
| 66 | DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) |
| 67 | return false; |
| 68 | |
| 69 | // See if this is an aligned allocation/deallocation function that is |
| 70 | // unavailable. |
| 71 | if (TreatUnavailableAsInvalid && |
| 72 | isUnavailableAlignedAllocationFunction(*FD)) |
| 73 | return false; |
| 74 | } |
| 75 | |
| 76 | // See if this function is unavailable. |
| 77 | if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && |
| 78 | cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) |
| 79 | return false; |
| 80 | |
| 81 | return true; |
| 82 | } |
| 83 | |
| 84 | static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { |
| 85 | // Warn if this is used but marked unused. |
| 86 | if (const auto *A = D->getAttr<UnusedAttr>()) { |
| 87 | // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) |
| 88 | // should diagnose them. |
| 89 | if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && |
| 90 | A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { |
| 91 | const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); |
| 92 | if (DC && !DC->hasAttr<UnusedAttr>()) |
| 93 | S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Emit a note explaining that this function is deleted. |
| 99 | void Sema::NoteDeletedFunction(FunctionDecl *Decl) { |
| 100 | assert(Decl->isDeleted()); |
| 101 | |
| 102 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); |
| 103 | |
| 104 | if (Method && Method->isDeleted() && Method->isDefaulted()) { |
| 105 | // If the method was explicitly defaulted, point at that declaration. |
| 106 | if (!Method->isImplicit()) |
| 107 | Diag(Decl->getLocation(), diag::note_implicitly_deleted); |
| 108 | |
| 109 | // Try to diagnose why this special member function was implicitly |
| 110 | // deleted. This might fail, if that reason no longer applies. |
| 111 | CXXSpecialMember CSM = getSpecialMember(Method); |
| 112 | if (CSM != CXXInvalid) |
| 113 | ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); |
| 114 | |
| 115 | return; |
| 116 | } |
| 117 | |
| 118 | auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); |
| 119 | if (Ctor && Ctor->isInheritingConstructor()) |
| 120 | return NoteDeletedInheritingConstructor(Ctor); |
| 121 | |
| 122 | Diag(Decl->getLocation(), diag::note_availability_specified_here) |
| 123 | << Decl << 1; |
| 124 | } |
| 125 | |
| 126 | /// Determine whether a FunctionDecl was ever declared with an |
| 127 | /// explicit storage class. |
| 128 | static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { |
| 129 | for (auto I : D->redecls()) { |
| 130 | if (I->getStorageClass() != SC_None) |
| 131 | return true; |
| 132 | } |
| 133 | return false; |
| 134 | } |
| 135 | |
| 136 | /// Check whether we're in an extern inline function and referring to a |
| 137 | /// variable or function with internal linkage (C11 6.7.4p3). |
| 138 | /// |
| 139 | /// This is only a warning because we used to silently accept this code, but |
| 140 | /// in many cases it will not behave correctly. This is not enabled in C++ mode |
| 141 | /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) |
| 142 | /// and so while there may still be user mistakes, most of the time we can't |
| 143 | /// prove that there are errors. |
| 144 | static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, |
| 145 | const NamedDecl *D, |
| 146 | SourceLocation Loc) { |
| 147 | // This is disabled under C++; there are too many ways for this to fire in |
| 148 | // contexts where the warning is a false positive, or where it is technically |
| 149 | // correct but benign. |
| 150 | if (S.getLangOpts().CPlusPlus) |
| 151 | return; |
| 152 | |
| 153 | // Check if this is an inlined function or method. |
| 154 | FunctionDecl *Current = S.getCurFunctionDecl(); |
| 155 | if (!Current) |
| 156 | return; |
| 157 | if (!Current->isInlined()) |
| 158 | return; |
| 159 | if (!Current->isExternallyVisible()) |
| 160 | return; |
| 161 | |
| 162 | // Check if the decl has internal linkage. |
| 163 | if (D->getFormalLinkage() != InternalLinkage) |
| 164 | return; |
| 165 | |
| 166 | // Downgrade from ExtWarn to Extension if |
| 167 | // (1) the supposedly external inline function is in the main file, |
| 168 | // and probably won't be included anywhere else. |
| 169 | // (2) the thing we're referencing is a pure function. |
| 170 | // (3) the thing we're referencing is another inline function. |
| 171 | // This last can give us false negatives, but it's better than warning on |
| 172 | // wrappers for simple C library functions. |
| 173 | const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); |
| 174 | bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); |
| 175 | if (!DowngradeWarning && UsedFn) |
| 176 | DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); |
| 177 | |
| 178 | S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet |
| 179 | : diag::ext_internal_in_extern_inline) |
| 180 | << /*IsVar=*/!UsedFn << D; |
| 181 | |
| 182 | S.MaybeSuggestAddingStaticToDecl(Current); |
| 183 | |
| 184 | S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) |
| 185 | << D; |
| 186 | } |
| 187 | |
| 188 | void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { |
| 189 | const FunctionDecl *First = Cur->getFirstDecl(); |
| 190 | |
| 191 | // Suggest "static" on the function, if possible. |
| 192 | if (!hasAnyExplicitStorageClass(First)) { |
| 193 | SourceLocation DeclBegin = First->getSourceRange().getBegin(); |
| 194 | Diag(DeclBegin, diag::note_convert_inline_to_static) |
| 195 | << Cur << FixItHint::CreateInsertion(DeclBegin, "static " ); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | /// Determine whether the use of this declaration is valid, and |
| 200 | /// emit any corresponding diagnostics. |
| 201 | /// |
| 202 | /// This routine diagnoses various problems with referencing |
| 203 | /// declarations that can occur when using a declaration. For example, |
| 204 | /// it might warn if a deprecated or unavailable declaration is being |
| 205 | /// used, or produce an error (and return true) if a C++0x deleted |
| 206 | /// function is being used. |
| 207 | /// |
| 208 | /// \returns true if there was an error (this declaration cannot be |
| 209 | /// referenced), false otherwise. |
| 210 | /// |
| 211 | bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, |
| 212 | const ObjCInterfaceDecl *UnknownObjCClass, |
| 213 | bool ObjCPropertyAccess, |
| 214 | bool AvoidPartialAvailabilityChecks, |
| 215 | ObjCInterfaceDecl *ClassReceiver) { |
| 216 | SourceLocation Loc = Locs.front(); |
| 217 | if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { |
| 218 | // If there were any diagnostics suppressed by template argument deduction, |
| 219 | // emit them now. |
| 220 | auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); |
| 221 | if (Pos != SuppressedDiagnostics.end()) { |
| 222 | for (const PartialDiagnosticAt &Suppressed : Pos->second) |
| 223 | Diag(Suppressed.first, Suppressed.second); |
| 224 | |
| 225 | // Clear out the list of suppressed diagnostics, so that we don't emit |
| 226 | // them again for this specialization. However, we don't obsolete this |
| 227 | // entry from the table, because we want to avoid ever emitting these |
| 228 | // diagnostics again. |
| 229 | Pos->second.clear(); |
| 230 | } |
| 231 | |
| 232 | // C++ [basic.start.main]p3: |
| 233 | // The function 'main' shall not be used within a program. |
| 234 | if (cast<FunctionDecl>(D)->isMain()) |
| 235 | Diag(Loc, diag::ext_main_used); |
| 236 | |
| 237 | diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); |
| 238 | } |
| 239 | |
| 240 | // See if this is an auto-typed variable whose initializer we are parsing. |
| 241 | if (ParsingInitForAutoVars.count(D)) { |
| 242 | if (isa<BindingDecl>(D)) { |
| 243 | Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) |
| 244 | << D->getDeclName(); |
| 245 | } else { |
| 246 | Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) |
| 247 | << D->getDeclName() << cast<VarDecl>(D)->getType(); |
| 248 | } |
| 249 | return true; |
| 250 | } |
| 251 | |
| 252 | // See if this is a deleted function. |
| 253 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 254 | if (FD->isDeleted()) { |
| 255 | auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); |
| 256 | if (Ctor && Ctor->isInheritingConstructor()) |
| 257 | Diag(Loc, diag::err_deleted_inherited_ctor_use) |
| 258 | << Ctor->getParent() |
| 259 | << Ctor->getInheritedConstructor().getConstructor()->getParent(); |
| 260 | else |
| 261 | Diag(Loc, diag::err_deleted_function_use); |
| 262 | NoteDeletedFunction(FD); |
| 263 | return true; |
| 264 | } |
| 265 | |
| 266 | // If the function has a deduced return type, and we can't deduce it, |
| 267 | // then we can't use it either. |
| 268 | if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && |
| 269 | DeduceReturnType(FD, Loc)) |
| 270 | return true; |
| 271 | |
| 272 | if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) |
| 273 | return true; |
| 274 | } |
| 275 | |
| 276 | if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { |
| 277 | // Lambdas are only default-constructible or assignable in C++2a onwards. |
| 278 | if (MD->getParent()->isLambda() && |
| 279 | ((isa<CXXConstructorDecl>(MD) && |
| 280 | cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || |
| 281 | MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { |
| 282 | Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) |
| 283 | << !isa<CXXConstructorDecl>(MD); |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | auto getReferencedObjCProp = [](const NamedDecl *D) -> |
| 288 | const ObjCPropertyDecl * { |
| 289 | if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) |
| 290 | return MD->findPropertyDecl(); |
| 291 | return nullptr; |
| 292 | }; |
| 293 | if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { |
| 294 | if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) |
| 295 | return true; |
| 296 | } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { |
| 297 | return true; |
| 298 | } |
| 299 | |
| 300 | // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions |
| 301 | // Only the variables omp_in and omp_out are allowed in the combiner. |
| 302 | // Only the variables omp_priv and omp_orig are allowed in the |
| 303 | // initializer-clause. |
| 304 | auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); |
| 305 | if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && |
| 306 | isa<VarDecl>(D)) { |
| 307 | Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) |
| 308 | << getCurFunction()->HasOMPDeclareReductionCombiner; |
| 309 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; |
| 310 | return true; |
| 311 | } |
| 312 | |
| 313 | // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions |
| 314 | // List-items in map clauses on this construct may only refer to the declared |
| 315 | // variable var and entities that could be referenced by a procedure defined |
| 316 | // at the same location |
| 317 | auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); |
| 318 | if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && |
| 319 | isa<VarDecl>(D)) { |
| 320 | Diag(Loc, diag::err_omp_declare_mapper_wrong_var) |
| 321 | << DMD->getVarName().getAsString(); |
| 322 | Diag(D->getLocation(), diag::note_entity_declared_at) << D; |
| 323 | return true; |
| 324 | } |
| 325 | |
| 326 | DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, |
| 327 | AvoidPartialAvailabilityChecks, ClassReceiver); |
| 328 | |
| 329 | DiagnoseUnusedOfDecl(*this, D, Loc); |
| 330 | |
| 331 | diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); |
| 332 | |
| 333 | return false; |
| 334 | } |
| 335 | |
| 336 | /// DiagnoseSentinelCalls - This routine checks whether a call or |
| 337 | /// message-send is to a declaration with the sentinel attribute, and |
| 338 | /// if so, it checks that the requirements of the sentinel are |
| 339 | /// satisfied. |
| 340 | void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, |
| 341 | ArrayRef<Expr *> Args) { |
| 342 | const SentinelAttr *attr = D->getAttr<SentinelAttr>(); |
| 343 | if (!attr) |
| 344 | return; |
| 345 | |
| 346 | // The number of formal parameters of the declaration. |
| 347 | unsigned numFormalParams; |
| 348 | |
| 349 | // The kind of declaration. This is also an index into a %select in |
| 350 | // the diagnostic. |
| 351 | enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; |
| 352 | |
| 353 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { |
| 354 | numFormalParams = MD->param_size(); |
| 355 | calleeType = CT_Method; |
| 356 | } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 357 | numFormalParams = FD->param_size(); |
| 358 | calleeType = CT_Function; |
| 359 | } else if (isa<VarDecl>(D)) { |
| 360 | QualType type = cast<ValueDecl>(D)->getType(); |
| 361 | const FunctionType *fn = nullptr; |
| 362 | if (const PointerType *ptr = type->getAs<PointerType>()) { |
| 363 | fn = ptr->getPointeeType()->getAs<FunctionType>(); |
| 364 | if (!fn) return; |
| 365 | calleeType = CT_Function; |
| 366 | } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { |
| 367 | fn = ptr->getPointeeType()->castAs<FunctionType>(); |
| 368 | calleeType = CT_Block; |
| 369 | } else { |
| 370 | return; |
| 371 | } |
| 372 | |
| 373 | if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { |
| 374 | numFormalParams = proto->getNumParams(); |
| 375 | } else { |
| 376 | numFormalParams = 0; |
| 377 | } |
| 378 | } else { |
| 379 | return; |
| 380 | } |
| 381 | |
| 382 | // "nullPos" is the number of formal parameters at the end which |
| 383 | // effectively count as part of the variadic arguments. This is |
| 384 | // useful if you would prefer to not have *any* formal parameters, |
| 385 | // but the language forces you to have at least one. |
| 386 | unsigned nullPos = attr->getNullPos(); |
| 387 | assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel" ); |
| 388 | numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); |
| 389 | |
| 390 | // The number of arguments which should follow the sentinel. |
| 391 | unsigned numArgsAfterSentinel = attr->getSentinel(); |
| 392 | |
| 393 | // If there aren't enough arguments for all the formal parameters, |
| 394 | // the sentinel, and the args after the sentinel, complain. |
| 395 | if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { |
| 396 | Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); |
| 397 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); |
| 398 | return; |
| 399 | } |
| 400 | |
| 401 | // Otherwise, find the sentinel expression. |
| 402 | Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; |
| 403 | if (!sentinelExpr) return; |
| 404 | if (sentinelExpr->isValueDependent()) return; |
| 405 | if (Context.isSentinelNullExpr(sentinelExpr)) return; |
| 406 | |
| 407 | // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', |
| 408 | // or 'NULL' if those are actually defined in the context. Only use |
| 409 | // 'nil' for ObjC methods, where it's much more likely that the |
| 410 | // variadic arguments form a list of object pointers. |
| 411 | SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); |
| 412 | std::string NullValue; |
| 413 | if (calleeType == CT_Method && PP.isMacroDefined("nil" )) |
| 414 | NullValue = "nil" ; |
| 415 | else if (getLangOpts().CPlusPlus11) |
| 416 | NullValue = "nullptr" ; |
| 417 | else if (PP.isMacroDefined("NULL" )) |
| 418 | NullValue = "NULL" ; |
| 419 | else |
| 420 | NullValue = "(void*) 0" ; |
| 421 | |
| 422 | if (MissingNilLoc.isInvalid()) |
| 423 | Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); |
| 424 | else |
| 425 | Diag(MissingNilLoc, diag::warn_missing_sentinel) |
| 426 | << int(calleeType) |
| 427 | << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); |
| 428 | Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); |
| 429 | } |
| 430 | |
| 431 | SourceRange Sema::getExprRange(Expr *E) const { |
| 432 | return E ? E->getSourceRange() : SourceRange(); |
| 433 | } |
| 434 | |
| 435 | //===----------------------------------------------------------------------===// |
| 436 | // Standard Promotions and Conversions |
| 437 | //===----------------------------------------------------------------------===// |
| 438 | |
| 439 | /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). |
| 440 | ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { |
| 441 | // Handle any placeholder expressions which made it here. |
| 442 | if (E->getType()->isPlaceholderType()) { |
| 443 | ExprResult result = CheckPlaceholderExpr(E); |
| 444 | if (result.isInvalid()) return ExprError(); |
| 445 | E = result.get(); |
| 446 | } |
| 447 | |
| 448 | QualType Ty = E->getType(); |
| 449 | assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type" ); |
| 450 | |
| 451 | if (Ty->isFunctionType()) { |
| 452 | if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) |
| 453 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) |
| 454 | if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) |
| 455 | return ExprError(); |
| 456 | |
| 457 | E = ImpCastExprToType(E, Context.getPointerType(Ty), |
| 458 | CK_FunctionToPointerDecay).get(); |
| 459 | } else if (Ty->isArrayType()) { |
| 460 | // In C90 mode, arrays only promote to pointers if the array expression is |
| 461 | // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has |
| 462 | // type 'array of type' is converted to an expression that has type 'pointer |
| 463 | // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression |
| 464 | // that has type 'array of type' ...". The relevant change is "an lvalue" |
| 465 | // (C90) to "an expression" (C99). |
| 466 | // |
| 467 | // C++ 4.2p1: |
| 468 | // An lvalue or rvalue of type "array of N T" or "array of unknown bound of |
| 469 | // T" can be converted to an rvalue of type "pointer to T". |
| 470 | // |
| 471 | if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) |
| 472 | E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), |
| 473 | CK_ArrayToPointerDecay).get(); |
| 474 | } |
| 475 | return E; |
| 476 | } |
| 477 | |
| 478 | static void CheckForNullPointerDereference(Sema &S, Expr *E) { |
| 479 | // Check to see if we are dereferencing a null pointer. If so, |
| 480 | // and if not volatile-qualified, this is undefined behavior that the |
| 481 | // optimizer will delete, so warn about it. People sometimes try to use this |
| 482 | // to get a deterministic trap and are surprised by clang's behavior. This |
| 483 | // only handles the pattern "*null", which is a very syntactic check. |
| 484 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) |
| 485 | if (UO->getOpcode() == UO_Deref && |
| 486 | UO->getSubExpr()->IgnoreParenCasts()-> |
| 487 | isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && |
| 488 | !UO->getType().isVolatileQualified()) { |
| 489 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, |
| 490 | S.PDiag(diag::warn_indirection_through_null) |
| 491 | << UO->getSubExpr()->getSourceRange()); |
| 492 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, |
| 493 | S.PDiag(diag::note_indirection_through_null)); |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, |
| 498 | SourceLocation AssignLoc, |
| 499 | const Expr* RHS) { |
| 500 | const ObjCIvarDecl *IV = OIRE->getDecl(); |
| 501 | if (!IV) |
| 502 | return; |
| 503 | |
| 504 | DeclarationName MemberName = IV->getDeclName(); |
| 505 | IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); |
| 506 | if (!Member || !Member->isStr("isa" )) |
| 507 | return; |
| 508 | |
| 509 | const Expr *Base = OIRE->getBase(); |
| 510 | QualType BaseType = Base->getType(); |
| 511 | if (OIRE->isArrow()) |
| 512 | BaseType = BaseType->getPointeeType(); |
| 513 | if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) |
| 514 | if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { |
| 515 | ObjCInterfaceDecl *ClassDeclared = nullptr; |
| 516 | ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); |
| 517 | if (!ClassDeclared->getSuperClass() |
| 518 | && (*ClassDeclared->ivar_begin()) == IV) { |
| 519 | if (RHS) { |
| 520 | NamedDecl *ObjectSetClass = |
| 521 | S.LookupSingleName(S.TUScope, |
| 522 | &S.Context.Idents.get("object_setClass" ), |
| 523 | SourceLocation(), S.LookupOrdinaryName); |
| 524 | if (ObjectSetClass) { |
| 525 | SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); |
| 526 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) |
| 527 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), |
| 528 | "object_setClass(" ) |
| 529 | << FixItHint::CreateReplacement( |
| 530 | SourceRange(OIRE->getOpLoc(), AssignLoc), "," ) |
| 531 | << FixItHint::CreateInsertion(RHSLocEnd, ")" ); |
| 532 | } |
| 533 | else |
| 534 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); |
| 535 | } else { |
| 536 | NamedDecl *ObjectGetClass = |
| 537 | S.LookupSingleName(S.TUScope, |
| 538 | &S.Context.Idents.get("object_getClass" ), |
| 539 | SourceLocation(), S.LookupOrdinaryName); |
| 540 | if (ObjectGetClass) |
| 541 | S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) |
| 542 | << FixItHint::CreateInsertion(OIRE->getBeginLoc(), |
| 543 | "object_getClass(" ) |
| 544 | << FixItHint::CreateReplacement( |
| 545 | SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")" ); |
| 546 | else |
| 547 | S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); |
| 548 | } |
| 549 | S.Diag(IV->getLocation(), diag::note_ivar_decl); |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | ExprResult Sema::DefaultLvalueConversion(Expr *E) { |
| 555 | if (E->getType().getQualifiers().hasOutput()) { |
| 556 | return ExprError(Diag(E->getExprLoc(), diag::err_typecheck_read_output) |
| 557 | << E->getSourceRange()); |
| 558 | } |
| 559 | |
| 560 | // Handle any placeholder expressions which made it here. |
| 561 | if (E->getType()->isPlaceholderType()) { |
| 562 | ExprResult result = CheckPlaceholderExpr(E); |
| 563 | if (result.isInvalid()) return ExprError(); |
| 564 | E = result.get(); |
| 565 | } |
| 566 | |
| 567 | // C++ [conv.lval]p1: |
| 568 | // A glvalue of a non-function, non-array type T can be |
| 569 | // converted to a prvalue. |
| 570 | if (!E->isGLValue()) return E; |
| 571 | |
| 572 | QualType T = E->getType(); |
| 573 | assert(!T.isNull() && "r-value conversion on typeless expression?" ); |
| 574 | |
| 575 | // We don't want to throw lvalue-to-rvalue casts on top of |
| 576 | // expressions of certain types in C++. |
| 577 | if (getLangOpts().CPlusPlus && |
| 578 | (E->getType() == Context.OverloadTy || |
| 579 | T->isDependentType() || |
| 580 | T->isRecordType())) |
| 581 | return E; |
| 582 | |
| 583 | // The C standard is actually really unclear on this point, and |
| 584 | // DR106 tells us what the result should be but not why. It's |
| 585 | // generally best to say that void types just doesn't undergo |
| 586 | // lvalue-to-rvalue at all. Note that expressions of unqualified |
| 587 | // 'void' type are never l-values, but qualified void can be. |
| 588 | if (T->isVoidType()) |
| 589 | return E; |
| 590 | |
| 591 | // OpenCL usually rejects direct accesses to values of 'half' type. |
| 592 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16" ) && |
| 593 | T->isHalfType()) { |
| 594 | Diag(E->getExprLoc(), diag::err_opencl_half_load_store) |
| 595 | << 0 << T; |
| 596 | return ExprError(); |
| 597 | } |
| 598 | |
| 599 | CheckForNullPointerDereference(*this, E); |
| 600 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { |
| 601 | NamedDecl *ObjectGetClass = LookupSingleName(TUScope, |
| 602 | &Context.Idents.get("object_getClass" ), |
| 603 | SourceLocation(), LookupOrdinaryName); |
| 604 | if (ObjectGetClass) |
| 605 | Diag(E->getExprLoc(), diag::warn_objc_isa_use) |
| 606 | << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(" ) |
| 607 | << FixItHint::CreateReplacement( |
| 608 | SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")" ); |
| 609 | else |
| 610 | Diag(E->getExprLoc(), diag::warn_objc_isa_use); |
| 611 | } |
| 612 | else if (const ObjCIvarRefExpr *OIRE = |
| 613 | dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) |
| 614 | DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); |
| 615 | |
| 616 | // C++ [conv.lval]p1: |
| 617 | // [...] If T is a non-class type, the type of the prvalue is the |
| 618 | // cv-unqualified version of T. Otherwise, the type of the |
| 619 | // rvalue is T. |
| 620 | // |
| 621 | // C99 6.3.2.1p2: |
| 622 | // If the lvalue has qualified type, the value has the unqualified |
| 623 | // version of the type of the lvalue; otherwise, the value has the |
| 624 | // type of the lvalue. |
| 625 | if (T.hasQualifiers()) |
| 626 | T = T.getUnqualifiedType(); |
| 627 | |
| 628 | // Under the MS ABI, lock down the inheritance model now. |
| 629 | if (T->isMemberPointerType() && |
| 630 | Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 631 | (void)isCompleteType(E->getExprLoc(), T); |
| 632 | |
| 633 | ExprResult Res = CheckLValueToRValueConversionOperand(E); |
| 634 | if (Res.isInvalid()) |
| 635 | return Res; |
| 636 | E = Res.get(); |
| 637 | |
| 638 | // Loading a __weak object implicitly retains the value, so we need a cleanup to |
| 639 | // balance that. |
| 640 | if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
| 641 | Cleanup.setExprNeedsCleanups(true); |
| 642 | |
| 643 | Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, nullptr, |
| 644 | VK_RValue); |
| 645 | |
| 646 | // C11 6.3.2.1p2: |
| 647 | // ... if the lvalue has atomic type, the value has the non-atomic version |
| 648 | // of the type of the lvalue ... |
| 649 | if (const AtomicType *Atomic = T->getAs<AtomicType>()) { |
| 650 | T = Atomic->getValueType().getUnqualifiedType(); |
| 651 | Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), |
| 652 | nullptr, VK_RValue); |
| 653 | } |
| 654 | |
| 655 | return Res; |
| 656 | } |
| 657 | |
| 658 | ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { |
| 659 | ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); |
| 660 | if (Res.isInvalid()) |
| 661 | return ExprError(); |
| 662 | Res = DefaultLvalueConversion(Res.get()); |
| 663 | if (Res.isInvalid()) |
| 664 | return ExprError(); |
| 665 | return Res; |
| 666 | } |
| 667 | |
| 668 | /// CallExprUnaryConversions - a special case of an unary conversion |
| 669 | /// performed on a function designator of a call expression. |
| 670 | ExprResult Sema::CallExprUnaryConversions(Expr *E) { |
| 671 | QualType Ty = E->getType(); |
| 672 | ExprResult Res = E; |
| 673 | // Only do implicit cast for a function type, but not for a pointer |
| 674 | // to function type. |
| 675 | if (Ty->isFunctionType()) { |
| 676 | Res = ImpCastExprToType(E, Context.getPointerType(Ty), |
| 677 | CK_FunctionToPointerDecay).get(); |
| 678 | if (Res.isInvalid()) |
| 679 | return ExprError(); |
| 680 | } |
| 681 | Res = DefaultLvalueConversion(Res.get()); |
| 682 | if (Res.isInvalid()) |
| 683 | return ExprError(); |
| 684 | return Res.get(); |
| 685 | } |
| 686 | |
| 687 | /// UsualUnaryConversions - Performs various conversions that are common to most |
| 688 | /// operators (C99 6.3). The conversions of array and function types are |
| 689 | /// sometimes suppressed. For example, the array->pointer conversion doesn't |
| 690 | /// apply if the array is an argument to the sizeof or address (&) operators. |
| 691 | /// In these instances, this routine should *not* be called. |
| 692 | ExprResult Sema::UsualUnaryConversions(Expr *E) { |
| 693 | // First, convert to an r-value. |
| 694 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
| 695 | if (Res.isInvalid()) |
| 696 | return ExprError(); |
| 697 | E = Res.get(); |
| 698 | |
| 699 | QualType Ty = E->getType(); |
| 700 | assert(!Ty.isNull() && "UsualUnaryConversions - missing type" ); |
| 701 | |
| 702 | // Half FP have to be promoted to float unless it is natively supported |
| 703 | if (Ty->isHalfType() && !getLangOpts().NativeHalfType) |
| 704 | return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); |
| 705 | |
| 706 | // Try to perform integral promotions if the object has a theoretically |
| 707 | // promotable type. |
| 708 | if (Ty->isIntegralOrUnscopedEnumerationType()) { |
| 709 | // C99 6.3.1.1p2: |
| 710 | // |
| 711 | // The following may be used in an expression wherever an int or |
| 712 | // unsigned int may be used: |
| 713 | // - an object or expression with an integer type whose integer |
| 714 | // conversion rank is less than or equal to the rank of int |
| 715 | // and unsigned int. |
| 716 | // - A bit-field of type _Bool, int, signed int, or unsigned int. |
| 717 | // |
| 718 | // If an int can represent all values of the original type, the |
| 719 | // value is converted to an int; otherwise, it is converted to an |
| 720 | // unsigned int. These are called the integer promotions. All |
| 721 | // other types are unchanged by the integer promotions. |
| 722 | |
| 723 | QualType PTy = Context.isPromotableBitField(E); |
| 724 | if (!PTy.isNull()) { |
| 725 | E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); |
| 726 | return E; |
| 727 | } |
| 728 | if (Ty->isPromotableIntegerType()) { |
| 729 | QualType PT = Context.getPromotedIntegerType(Ty); |
| 730 | E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); |
| 731 | return E; |
| 732 | } |
| 733 | } |
| 734 | return E; |
| 735 | } |
| 736 | |
| 737 | /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that |
| 738 | /// do not have a prototype. Arguments that have type float or __fp16 |
| 739 | /// are promoted to double. All other argument types are converted by |
| 740 | /// UsualUnaryConversions(). |
| 741 | ExprResult Sema::DefaultArgumentPromotion(Expr *E) { |
| 742 | QualType Ty = E->getType(); |
| 743 | assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type" ); |
| 744 | |
| 745 | ExprResult Res = UsualUnaryConversions(E); |
| 746 | if (Res.isInvalid()) |
| 747 | return ExprError(); |
| 748 | E = Res.get(); |
| 749 | |
| 750 | // If this is a 'float' or '__fp16' (CVR qualified or typedef) |
| 751 | // promote to double. |
| 752 | // Note that default argument promotion applies only to float (and |
| 753 | // half/fp16); it does not apply to _Float16. |
| 754 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
| 755 | if (BTy && (BTy->getKind() == BuiltinType::Half || |
| 756 | BTy->getKind() == BuiltinType::Float)) { |
| 757 | if (getLangOpts().OpenCL && |
| 758 | !getOpenCLOptions().isEnabled("cl_khr_fp64" )) { |
| 759 | if (BTy->getKind() == BuiltinType::Half) { |
| 760 | E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); |
| 761 | } |
| 762 | } else { |
| 763 | E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | // C++ performs lvalue-to-rvalue conversion as a default argument |
| 768 | // promotion, even on class types, but note: |
| 769 | // C++11 [conv.lval]p2: |
| 770 | // When an lvalue-to-rvalue conversion occurs in an unevaluated |
| 771 | // operand or a subexpression thereof the value contained in the |
| 772 | // referenced object is not accessed. Otherwise, if the glvalue |
| 773 | // has a class type, the conversion copy-initializes a temporary |
| 774 | // of type T from the glvalue and the result of the conversion |
| 775 | // is a prvalue for the temporary. |
| 776 | // FIXME: add some way to gate this entire thing for correctness in |
| 777 | // potentially potentially evaluated contexts. |
| 778 | if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { |
| 779 | ExprResult Temp = PerformCopyInitialization( |
| 780 | InitializedEntity::InitializeTemporary(E->getType()), |
| 781 | E->getExprLoc(), E); |
| 782 | if (Temp.isInvalid()) |
| 783 | return ExprError(); |
| 784 | E = Temp.get(); |
| 785 | } |
| 786 | |
| 787 | return E; |
| 788 | } |
| 789 | |
| 790 | /// Determine the degree of POD-ness for an expression. |
| 791 | /// Incomplete types are considered POD, since this check can be performed |
| 792 | /// when we're in an unevaluated context. |
| 793 | Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { |
| 794 | if (Ty->isIncompleteType()) { |
| 795 | // C++11 [expr.call]p7: |
| 796 | // After these conversions, if the argument does not have arithmetic, |
| 797 | // enumeration, pointer, pointer to member, or class type, the program |
| 798 | // is ill-formed. |
| 799 | // |
| 800 | // Since we've already performed array-to-pointer and function-to-pointer |
| 801 | // decay, the only such type in C++ is cv void. This also handles |
| 802 | // initializer lists as variadic arguments. |
| 803 | if (Ty->isVoidType()) |
| 804 | return VAK_Invalid; |
| 805 | |
| 806 | if (Ty->isObjCObjectType()) |
| 807 | return VAK_Invalid; |
| 808 | return VAK_Valid; |
| 809 | } |
| 810 | |
| 811 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
| 812 | return VAK_Invalid; |
| 813 | |
| 814 | if (Ty.isCXX98PODType(Context)) |
| 815 | return VAK_Valid; |
| 816 | |
| 817 | // C++11 [expr.call]p7: |
| 818 | // Passing a potentially-evaluated argument of class type (Clause 9) |
| 819 | // having a non-trivial copy constructor, a non-trivial move constructor, |
| 820 | // or a non-trivial destructor, with no corresponding parameter, |
| 821 | // is conditionally-supported with implementation-defined semantics. |
| 822 | if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) |
| 823 | if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) |
| 824 | if (!Record->hasNonTrivialCopyConstructor() && |
| 825 | !Record->hasNonTrivialMoveConstructor() && |
| 826 | !Record->hasNonTrivialDestructor()) |
| 827 | return VAK_ValidInCXX11; |
| 828 | |
| 829 | if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) |
| 830 | return VAK_Valid; |
| 831 | |
| 832 | if (Ty->isObjCObjectType()) |
| 833 | return VAK_Invalid; |
| 834 | |
| 835 | if (getLangOpts().MSVCCompat) |
| 836 | return VAK_MSVCUndefined; |
| 837 | |
| 838 | // FIXME: In C++11, these cases are conditionally-supported, meaning we're |
| 839 | // permitted to reject them. We should consider doing so. |
| 840 | return VAK_Undefined; |
| 841 | } |
| 842 | |
| 843 | void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { |
| 844 | // Don't allow one to pass an Objective-C interface to a vararg. |
| 845 | const QualType &Ty = E->getType(); |
| 846 | VarArgKind VAK = isValidVarArgType(Ty); |
| 847 | |
| 848 | if (Ty->isCHERICapabilityType(Context)) |
| 849 | if (Context.getTargetInfo().getTriple().isMIPS() && |
| 850 | !Context.getTargetInfo().areAllPointersCapabilities()) |
| 851 | Diag(E->getBeginLoc(), diag::warn_capabilities_broken_in_hybrid_varargs) |
| 852 | << E->getSourceRange(); |
| 853 | |
| 854 | // Complain about passing non-POD types through varargs. |
| 855 | switch (VAK) { |
| 856 | case VAK_ValidInCXX11: |
| 857 | DiagRuntimeBehavior( |
| 858 | E->getBeginLoc(), nullptr, |
| 859 | PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); |
| 860 | LLVM_FALLTHROUGH; |
| 861 | case VAK_Valid: |
| 862 | if (Ty->isRecordType()) { |
| 863 | // This is unlikely to be what the user intended. If the class has a |
| 864 | // 'c_str' member function, the user probably meant to call that. |
| 865 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, |
| 866 | PDiag(diag::warn_pass_class_arg_to_vararg) |
| 867 | << Ty << CT << hasCStrMethod(E) << ".c_str()" ); |
| 868 | } |
| 869 | break; |
| 870 | |
| 871 | case VAK_Undefined: |
| 872 | case VAK_MSVCUndefined: |
| 873 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, |
| 874 | PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) |
| 875 | << getLangOpts().CPlusPlus11 << Ty << CT); |
| 876 | break; |
| 877 | |
| 878 | case VAK_Invalid: |
| 879 | if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) |
| 880 | Diag(E->getBeginLoc(), |
| 881 | diag::err_cannot_pass_non_trivial_c_struct_to_vararg) |
| 882 | << Ty << CT; |
| 883 | else if (Ty->isObjCObjectType()) |
| 884 | DiagRuntimeBehavior(E->getBeginLoc(), nullptr, |
| 885 | PDiag(diag::err_cannot_pass_objc_interface_to_vararg) |
| 886 | << Ty << CT); |
| 887 | else |
| 888 | Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) |
| 889 | << isa<InitListExpr>(E) << Ty << CT; |
| 890 | break; |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but |
| 895 | /// will create a trap if the resulting type is not a POD type. |
| 896 | ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, |
| 897 | FunctionDecl *FDecl) { |
| 898 | if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { |
| 899 | // Strip the unbridged-cast placeholder expression off, if applicable. |
| 900 | if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && |
| 901 | (CT == VariadicMethod || |
| 902 | (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { |
| 903 | E = stripARCUnbridgedCast(E); |
| 904 | |
| 905 | // Otherwise, do normal placeholder checking. |
| 906 | } else { |
| 907 | ExprResult ExprRes = CheckPlaceholderExpr(E); |
| 908 | if (ExprRes.isInvalid()) |
| 909 | return ExprError(); |
| 910 | E = ExprRes.get(); |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | ExprResult ExprRes = DefaultArgumentPromotion(E); |
| 915 | if (ExprRes.isInvalid()) |
| 916 | return ExprError(); |
| 917 | E = ExprRes.get(); |
| 918 | |
| 919 | // Diagnostics regarding non-POD argument types are |
| 920 | // emitted along with format string checking in Sema::CheckFunctionCall(). |
| 921 | if (isValidVarArgType(E->getType()) == VAK_Undefined) { |
| 922 | // Turn this into a trap. |
| 923 | CXXScopeSpec SS; |
| 924 | SourceLocation TemplateKWLoc; |
| 925 | UnqualifiedId Name; |
| 926 | Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap" ), |
| 927 | E->getBeginLoc()); |
| 928 | ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, |
| 929 | /*HasTrailingLParen=*/true, |
| 930 | /*IsAddressOfOperand=*/false); |
| 931 | if (TrapFn.isInvalid()) |
| 932 | return ExprError(); |
| 933 | |
| 934 | ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), |
| 935 | None, E->getEndLoc()); |
| 936 | if (Call.isInvalid()) |
| 937 | return ExprError(); |
| 938 | |
| 939 | ExprResult Comma = |
| 940 | ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); |
| 941 | if (Comma.isInvalid()) |
| 942 | return ExprError(); |
| 943 | return Comma.get(); |
| 944 | } |
| 945 | |
| 946 | if (!getLangOpts().CPlusPlus && |
| 947 | RequireCompleteType(E->getExprLoc(), E->getType(), |
| 948 | diag::err_call_incomplete_argument)) |
| 949 | return ExprError(); |
| 950 | |
| 951 | return E; |
| 952 | } |
| 953 | |
| 954 | /// Converts an integer to complex float type. Helper function of |
| 955 | /// UsualArithmeticConversions() |
| 956 | /// |
| 957 | /// \return false if the integer expression is an integer type and is |
| 958 | /// successfully converted to the complex type. |
| 959 | static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, |
| 960 | ExprResult &ComplexExpr, |
| 961 | QualType IntTy, |
| 962 | QualType ComplexTy, |
| 963 | bool SkipCast) { |
| 964 | if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; |
| 965 | if (SkipCast) return false; |
| 966 | if (IntTy->isIntegerType()) { |
| 967 | QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); |
| 968 | IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); |
| 969 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, |
| 970 | CK_FloatingRealToComplex); |
| 971 | } else { |
| 972 | assert(IntTy->isComplexIntegerType()); |
| 973 | IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, |
| 974 | CK_IntegralComplexToFloatingComplex); |
| 975 | } |
| 976 | return false; |
| 977 | } |
| 978 | |
| 979 | /// Handle arithmetic conversion with complex types. Helper function of |
| 980 | /// UsualArithmeticConversions() |
| 981 | static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, |
| 982 | ExprResult &RHS, QualType LHSType, |
| 983 | QualType RHSType, |
| 984 | bool IsCompAssign) { |
| 985 | // if we have an integer operand, the result is the complex type. |
| 986 | if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, |
| 987 | /*skipCast*/false)) |
| 988 | return LHSType; |
| 989 | if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, |
| 990 | /*skipCast*/IsCompAssign)) |
| 991 | return RHSType; |
| 992 | |
| 993 | // This handles complex/complex, complex/float, or float/complex. |
| 994 | // When both operands are complex, the shorter operand is converted to the |
| 995 | // type of the longer, and that is the type of the result. This corresponds |
| 996 | // to what is done when combining two real floating-point operands. |
| 997 | // The fun begins when size promotion occur across type domains. |
| 998 | // From H&S 6.3.4: When one operand is complex and the other is a real |
| 999 | // floating-point type, the less precise type is converted, within it's |
| 1000 | // real or complex domain, to the precision of the other type. For example, |
| 1001 | // when combining a "long double" with a "double _Complex", the |
| 1002 | // "double _Complex" is promoted to "long double _Complex". |
| 1003 | |
| 1004 | // Compute the rank of the two types, regardless of whether they are complex. |
| 1005 | int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); |
| 1006 | |
| 1007 | auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); |
| 1008 | auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); |
| 1009 | QualType LHSElementType = |
| 1010 | LHSComplexType ? LHSComplexType->getElementType() : LHSType; |
| 1011 | QualType RHSElementType = |
| 1012 | RHSComplexType ? RHSComplexType->getElementType() : RHSType; |
| 1013 | |
| 1014 | QualType ResultType = S.Context.getComplexType(LHSElementType); |
| 1015 | if (Order < 0) { |
| 1016 | // Promote the precision of the LHS if not an assignment. |
| 1017 | ResultType = S.Context.getComplexType(RHSElementType); |
| 1018 | if (!IsCompAssign) { |
| 1019 | if (LHSComplexType) |
| 1020 | LHS = |
| 1021 | S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); |
| 1022 | else |
| 1023 | LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); |
| 1024 | } |
| 1025 | } else if (Order > 0) { |
| 1026 | // Promote the precision of the RHS. |
| 1027 | if (RHSComplexType) |
| 1028 | RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); |
| 1029 | else |
| 1030 | RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); |
| 1031 | } |
| 1032 | return ResultType; |
| 1033 | } |
| 1034 | |
| 1035 | /// Handle arithmetic conversion from integer to float. Helper function |
| 1036 | /// of UsualArithmeticConversions() |
| 1037 | static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, |
| 1038 | ExprResult &IntExpr, |
| 1039 | QualType FloatTy, QualType IntTy, |
| 1040 | bool ConvertFloat, bool ConvertInt) { |
| 1041 | if (IntTy->isIntegerType()) { |
| 1042 | if (ConvertInt) |
| 1043 | // Convert intExpr to the lhs floating point type. |
| 1044 | IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, |
| 1045 | CK_IntegralToFloating); |
| 1046 | return FloatTy; |
| 1047 | } |
| 1048 | |
| 1049 | // Convert both sides to the appropriate complex float. |
| 1050 | assert(IntTy->isComplexIntegerType()); |
| 1051 | QualType result = S.Context.getComplexType(FloatTy); |
| 1052 | |
| 1053 | // _Complex int -> _Complex float |
| 1054 | if (ConvertInt) |
| 1055 | IntExpr = S.ImpCastExprToType(IntExpr.get(), result, |
| 1056 | CK_IntegralComplexToFloatingComplex); |
| 1057 | |
| 1058 | // float -> _Complex float |
| 1059 | if (ConvertFloat) |
| 1060 | FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, |
| 1061 | CK_FloatingRealToComplex); |
| 1062 | |
| 1063 | return result; |
| 1064 | } |
| 1065 | |
| 1066 | /// Handle arithmethic conversion with floating point types. Helper |
| 1067 | /// function of UsualArithmeticConversions() |
| 1068 | static QualType handleFloatConversion(Sema &S, ExprResult &LHS, |
| 1069 | ExprResult &RHS, QualType LHSType, |
| 1070 | QualType RHSType, bool IsCompAssign) { |
| 1071 | bool LHSFloat = LHSType->isRealFloatingType(); |
| 1072 | bool RHSFloat = RHSType->isRealFloatingType(); |
| 1073 | |
| 1074 | // If we have two real floating types, convert the smaller operand |
| 1075 | // to the bigger result. |
| 1076 | if (LHSFloat && RHSFloat) { |
| 1077 | int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); |
| 1078 | if (order > 0) { |
| 1079 | RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); |
| 1080 | return LHSType; |
| 1081 | } |
| 1082 | |
| 1083 | assert(order < 0 && "illegal float comparison" ); |
| 1084 | if (!IsCompAssign) |
| 1085 | LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); |
| 1086 | return RHSType; |
| 1087 | } |
| 1088 | |
| 1089 | if (LHSFloat) { |
| 1090 | // Half FP has to be promoted to float unless it is natively supported |
| 1091 | if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) |
| 1092 | LHSType = S.Context.FloatTy; |
| 1093 | |
| 1094 | return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, |
| 1095 | /*convertFloat=*/!IsCompAssign, |
| 1096 | /*convertInt=*/ true); |
| 1097 | } |
| 1098 | assert(RHSFloat); |
| 1099 | return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, |
| 1100 | /*convertInt=*/ true, |
| 1101 | /*convertFloat=*/!IsCompAssign); |
| 1102 | } |
| 1103 | |
| 1104 | /// Diagnose attempts to convert between __float128 and long double if |
| 1105 | /// there is no support for such conversion. Helper function of |
| 1106 | /// UsualArithmeticConversions(). |
| 1107 | static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, |
| 1108 | QualType RHSType) { |
| 1109 | /* No issue converting if at least one of the types is not a floating point |
| 1110 | type or the two types have the same rank. |
| 1111 | */ |
| 1112 | if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || |
| 1113 | S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) |
| 1114 | return false; |
| 1115 | |
| 1116 | assert(LHSType->isFloatingType() && RHSType->isFloatingType() && |
| 1117 | "The remaining types must be floating point types." ); |
| 1118 | |
| 1119 | auto *LHSComplex = LHSType->getAs<ComplexType>(); |
| 1120 | auto *RHSComplex = RHSType->getAs<ComplexType>(); |
| 1121 | |
| 1122 | QualType LHSElemType = LHSComplex ? |
| 1123 | LHSComplex->getElementType() : LHSType; |
| 1124 | QualType RHSElemType = RHSComplex ? |
| 1125 | RHSComplex->getElementType() : RHSType; |
| 1126 | |
| 1127 | // No issue if the two types have the same representation |
| 1128 | if (&S.Context.getFloatTypeSemantics(LHSElemType) == |
| 1129 | &S.Context.getFloatTypeSemantics(RHSElemType)) |
| 1130 | return false; |
| 1131 | |
| 1132 | bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && |
| 1133 | RHSElemType == S.Context.LongDoubleTy); |
| 1134 | Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && |
| 1135 | RHSElemType == S.Context.Float128Ty); |
| 1136 | |
| 1137 | // We've handled the situation where __float128 and long double have the same |
| 1138 | // representation. We allow all conversions for all possible long double types |
| 1139 | // except PPC's double double. |
| 1140 | return Float128AndLongDouble && |
| 1141 | (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == |
| 1142 | &llvm::APFloat::PPCDoubleDouble()); |
| 1143 | } |
| 1144 | |
| 1145 | typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); |
| 1146 | |
| 1147 | namespace { |
| 1148 | /// These helper callbacks are placed in an anonymous namespace to |
| 1149 | /// permit their use as function template parameters. |
| 1150 | ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { |
| 1151 | return S.ImpCastExprToType(op, toType, CK_IntegralCast); |
| 1152 | } |
| 1153 | |
| 1154 | ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { |
| 1155 | return S.ImpCastExprToType(op, S.Context.getComplexType(toType), |
| 1156 | CK_IntegralComplexCast); |
| 1157 | } |
| 1158 | } |
| 1159 | |
| 1160 | /// Handle integer arithmetic conversions. Helper function of |
| 1161 | /// UsualArithmeticConversions() |
| 1162 | template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> |
| 1163 | static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, |
| 1164 | ExprResult &RHS, QualType LHSType, |
| 1165 | QualType RHSType, bool IsCompAssign) { |
| 1166 | // The rules for this case are in C99 6.3.1.8 |
| 1167 | int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); |
| 1168 | bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); |
| 1169 | bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); |
| 1170 | if (LHSSigned == RHSSigned) { |
| 1171 | // Same signedness; use the higher-ranked type |
| 1172 | if (order >= 0) { |
| 1173 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
| 1174 | return LHSType; |
| 1175 | } else if (!IsCompAssign) |
| 1176 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
| 1177 | return RHSType; |
| 1178 | } else if (order != (LHSSigned ? 1 : -1)) { |
| 1179 | // The unsigned type has greater than or equal rank to the |
| 1180 | // signed type, so use the unsigned type |
| 1181 | if (RHSSigned) { |
| 1182 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
| 1183 | return LHSType; |
| 1184 | } else if (!IsCompAssign) |
| 1185 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
| 1186 | return RHSType; |
| 1187 | } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { |
| 1188 | // The two types are different widths; if we are here, that |
| 1189 | // means the signed type is larger than the unsigned type, so |
| 1190 | // use the signed type. |
| 1191 | if (LHSSigned) { |
| 1192 | RHS = (*doRHSCast)(S, RHS.get(), LHSType); |
| 1193 | return LHSType; |
| 1194 | } else if (!IsCompAssign) |
| 1195 | LHS = (*doLHSCast)(S, LHS.get(), RHSType); |
| 1196 | return RHSType; |
| 1197 | } else { |
| 1198 | // The signed type is higher-ranked than the unsigned type, |
| 1199 | // but isn't actually any bigger (like unsigned int and long |
| 1200 | // on most 32-bit systems). Use the unsigned type corresponding |
| 1201 | // to the signed type. |
| 1202 | QualType result = |
| 1203 | S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); |
| 1204 | RHS = (*doRHSCast)(S, RHS.get(), result); |
| 1205 | if (!IsCompAssign) |
| 1206 | LHS = (*doLHSCast)(S, LHS.get(), result); |
| 1207 | return result; |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | /// Handle conversions with GCC complex int extension. Helper function |
| 1212 | /// of UsualArithmeticConversions() |
| 1213 | static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, |
| 1214 | ExprResult &RHS, QualType LHSType, |
| 1215 | QualType RHSType, |
| 1216 | bool IsCompAssign) { |
| 1217 | const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); |
| 1218 | const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); |
| 1219 | |
| 1220 | if (LHSComplexInt && RHSComplexInt) { |
| 1221 | QualType LHSEltType = LHSComplexInt->getElementType(); |
| 1222 | QualType RHSEltType = RHSComplexInt->getElementType(); |
| 1223 | QualType ScalarType = |
| 1224 | handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> |
| 1225 | (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); |
| 1226 | |
| 1227 | return S.Context.getComplexType(ScalarType); |
| 1228 | } |
| 1229 | |
| 1230 | if (LHSComplexInt) { |
| 1231 | QualType LHSEltType = LHSComplexInt->getElementType(); |
| 1232 | QualType ScalarType = |
| 1233 | handleIntegerConversion<doComplexIntegralCast, doIntegralCast> |
| 1234 | (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); |
| 1235 | QualType ComplexType = S.Context.getComplexType(ScalarType); |
| 1236 | RHS = S.ImpCastExprToType(RHS.get(), ComplexType, |
| 1237 | CK_IntegralRealToComplex); |
| 1238 | |
| 1239 | return ComplexType; |
| 1240 | } |
| 1241 | |
| 1242 | assert(RHSComplexInt); |
| 1243 | |
| 1244 | QualType RHSEltType = RHSComplexInt->getElementType(); |
| 1245 | QualType ScalarType = |
| 1246 | handleIntegerConversion<doIntegralCast, doComplexIntegralCast> |
| 1247 | (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); |
| 1248 | QualType ComplexType = S.Context.getComplexType(ScalarType); |
| 1249 | |
| 1250 | if (!IsCompAssign) |
| 1251 | LHS = S.ImpCastExprToType(LHS.get(), ComplexType, |
| 1252 | CK_IntegralRealToComplex); |
| 1253 | return ComplexType; |
| 1254 | } |
| 1255 | |
| 1256 | /// Return the rank of a given fixed point or integer type. The value itself |
| 1257 | /// doesn't matter, but the values must be increasing with proper increasing |
| 1258 | /// rank as described in N1169 4.1.1. |
| 1259 | static unsigned GetFixedPointRank(QualType Ty) { |
| 1260 | const auto *BTy = Ty->getAs<BuiltinType>(); |
| 1261 | assert(BTy && "Expected a builtin type." ); |
| 1262 | |
| 1263 | switch (BTy->getKind()) { |
| 1264 | case BuiltinType::ShortFract: |
| 1265 | case BuiltinType::UShortFract: |
| 1266 | case BuiltinType::SatShortFract: |
| 1267 | case BuiltinType::SatUShortFract: |
| 1268 | return 1; |
| 1269 | case BuiltinType::Fract: |
| 1270 | case BuiltinType::UFract: |
| 1271 | case BuiltinType::SatFract: |
| 1272 | case BuiltinType::SatUFract: |
| 1273 | return 2; |
| 1274 | case BuiltinType::LongFract: |
| 1275 | case BuiltinType::ULongFract: |
| 1276 | case BuiltinType::SatLongFract: |
| 1277 | case BuiltinType::SatULongFract: |
| 1278 | return 3; |
| 1279 | case BuiltinType::ShortAccum: |
| 1280 | case BuiltinType::UShortAccum: |
| 1281 | case BuiltinType::SatShortAccum: |
| 1282 | case BuiltinType::SatUShortAccum: |
| 1283 | return 4; |
| 1284 | case BuiltinType::Accum: |
| 1285 | case BuiltinType::UAccum: |
| 1286 | case BuiltinType::SatAccum: |
| 1287 | case BuiltinType::SatUAccum: |
| 1288 | return 5; |
| 1289 | case BuiltinType::LongAccum: |
| 1290 | case BuiltinType::ULongAccum: |
| 1291 | case BuiltinType::SatLongAccum: |
| 1292 | case BuiltinType::SatULongAccum: |
| 1293 | return 6; |
| 1294 | default: |
| 1295 | if (BTy->isInteger()) |
| 1296 | return 0; |
| 1297 | llvm_unreachable("Unexpected fixed point or integer type" ); |
| 1298 | } |
| 1299 | } |
| 1300 | |
| 1301 | /// handleFixedPointConversion - Fixed point operations between fixed |
| 1302 | /// point types and integers or other fixed point types do not fall under |
| 1303 | /// usual arithmetic conversion since these conversions could result in loss |
| 1304 | /// of precsision (N1169 4.1.4). These operations should be calculated with |
| 1305 | /// the full precision of their result type (N1169 4.1.6.2.1). |
| 1306 | static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, |
| 1307 | QualType RHSTy) { |
| 1308 | assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && |
| 1309 | "Expected at least one of the operands to be a fixed point type" ); |
| 1310 | assert((LHSTy->isFixedPointOrIntegerType() || |
| 1311 | RHSTy->isFixedPointOrIntegerType()) && |
| 1312 | "Special fixed point arithmetic operation conversions are only " |
| 1313 | "applied to ints or other fixed point types" ); |
| 1314 | |
| 1315 | // If one operand has signed fixed-point type and the other operand has |
| 1316 | // unsigned fixed-point type, then the unsigned fixed-point operand is |
| 1317 | // converted to its corresponding signed fixed-point type and the resulting |
| 1318 | // type is the type of the converted operand. |
| 1319 | if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) |
| 1320 | LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); |
| 1321 | else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) |
| 1322 | RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); |
| 1323 | |
| 1324 | // The result type is the type with the highest rank, whereby a fixed-point |
| 1325 | // conversion rank is always greater than an integer conversion rank; if the |
| 1326 | // type of either of the operands is a saturating fixedpoint type, the result |
| 1327 | // type shall be the saturating fixed-point type corresponding to the type |
| 1328 | // with the highest rank; the resulting value is converted (taking into |
| 1329 | // account rounding and overflow) to the precision of the resulting type. |
| 1330 | // Same ranks between signed and unsigned types are resolved earlier, so both |
| 1331 | // types are either signed or both unsigned at this point. |
| 1332 | unsigned LHSTyRank = GetFixedPointRank(LHSTy); |
| 1333 | unsigned RHSTyRank = GetFixedPointRank(RHSTy); |
| 1334 | |
| 1335 | QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; |
| 1336 | |
| 1337 | if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) |
| 1338 | ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); |
| 1339 | |
| 1340 | return ResultTy; |
| 1341 | } |
| 1342 | |
| 1343 | /// UsualArithmeticConversions - Performs various conversions that are common to |
| 1344 | /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this |
| 1345 | /// routine returns the first non-arithmetic type found. The client is |
| 1346 | /// responsible for emitting appropriate error diagnostics. |
| 1347 | QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, |
| 1348 | bool IsCompAssign) { |
| 1349 | if (!IsCompAssign) { |
| 1350 | LHS = UsualUnaryConversions(LHS.get()); |
| 1351 | if (LHS.isInvalid()) |
| 1352 | return QualType(); |
| 1353 | } |
| 1354 | |
| 1355 | RHS = UsualUnaryConversions(RHS.get()); |
| 1356 | if (RHS.isInvalid()) |
| 1357 | return QualType(); |
| 1358 | |
| 1359 | // For conversion purposes, we ignore any qualifiers. |
| 1360 | // For example, "const float" and "float" are equivalent. |
| 1361 | QualType LHSType = |
| 1362 | Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); |
| 1363 | QualType RHSType = |
| 1364 | Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); |
| 1365 | |
| 1366 | // For conversion purposes, we ignore any atomic qualifier on the LHS. |
| 1367 | if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) |
| 1368 | LHSType = AtomicLHS->getValueType(); |
| 1369 | |
| 1370 | // If both types are identical, no conversion is needed. |
| 1371 | if (LHSType == RHSType) |
| 1372 | return LHSType; |
| 1373 | |
| 1374 | // If either side is a non-arithmetic type (e.g. a pointer), we are done. |
| 1375 | // The caller can deal with this (e.g. pointer + int). |
| 1376 | if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) |
| 1377 | return QualType(); |
| 1378 | |
| 1379 | // Apply unary and bitfield promotions to the LHS's type. |
| 1380 | QualType LHSUnpromotedType = LHSType; |
| 1381 | if (LHSType->isPromotableIntegerType()) |
| 1382 | LHSType = Context.getPromotedIntegerType(LHSType); |
| 1383 | QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); |
| 1384 | if (!LHSBitfieldPromoteTy.isNull()) |
| 1385 | LHSType = LHSBitfieldPromoteTy; |
| 1386 | if (LHSType != LHSUnpromotedType && !IsCompAssign) |
| 1387 | LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); |
| 1388 | |
| 1389 | // If both types are identical, no conversion is needed. |
| 1390 | if (LHSType == RHSType) |
| 1391 | return LHSType; |
| 1392 | |
| 1393 | // At this point, we have two different arithmetic types. |
| 1394 | |
| 1395 | // Diagnose attempts to convert between __float128 and long double where |
| 1396 | // such conversions currently can't be handled. |
| 1397 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) |
| 1398 | return QualType(); |
| 1399 | |
| 1400 | // Handle complex types first (C99 6.3.1.8p1). |
| 1401 | if (LHSType->isComplexType() || RHSType->isComplexType()) |
| 1402 | return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, |
| 1403 | IsCompAssign); |
| 1404 | |
| 1405 | // Now handle "real" floating types (i.e. float, double, long double). |
| 1406 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
| 1407 | return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, |
| 1408 | IsCompAssign); |
| 1409 | |
| 1410 | // Handle GCC complex int extension. |
| 1411 | if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) |
| 1412 | return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, |
| 1413 | IsCompAssign); |
| 1414 | |
| 1415 | if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) |
| 1416 | return handleFixedPointConversion(*this, LHSType, RHSType); |
| 1417 | |
| 1418 | // Finally, we have two differing integer types. |
| 1419 | return handleIntegerConversion<doIntegralCast, doIntegralCast> |
| 1420 | (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); |
| 1421 | } |
| 1422 | |
| 1423 | //===----------------------------------------------------------------------===// |
| 1424 | // Semantic Analysis for various Expression Types |
| 1425 | //===----------------------------------------------------------------------===// |
| 1426 | |
| 1427 | |
| 1428 | ExprResult |
| 1429 | Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, |
| 1430 | SourceLocation DefaultLoc, |
| 1431 | SourceLocation RParenLoc, |
| 1432 | Expr *ControllingExpr, |
| 1433 | ArrayRef<ParsedType> ArgTypes, |
| 1434 | ArrayRef<Expr *> ArgExprs) { |
| 1435 | unsigned NumAssocs = ArgTypes.size(); |
| 1436 | assert(NumAssocs == ArgExprs.size()); |
| 1437 | |
| 1438 | TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; |
| 1439 | for (unsigned i = 0; i < NumAssocs; ++i) { |
| 1440 | if (ArgTypes[i]) |
| 1441 | (void) GetTypeFromParser(ArgTypes[i], &Types[i]); |
| 1442 | else |
| 1443 | Types[i] = nullptr; |
| 1444 | } |
| 1445 | |
| 1446 | ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, |
| 1447 | ControllingExpr, |
| 1448 | llvm::makeArrayRef(Types, NumAssocs), |
| 1449 | ArgExprs); |
| 1450 | delete [] Types; |
| 1451 | return ER; |
| 1452 | } |
| 1453 | |
| 1454 | ExprResult |
| 1455 | Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, |
| 1456 | SourceLocation DefaultLoc, |
| 1457 | SourceLocation RParenLoc, |
| 1458 | Expr *ControllingExpr, |
| 1459 | ArrayRef<TypeSourceInfo *> Types, |
| 1460 | ArrayRef<Expr *> Exprs) { |
| 1461 | unsigned NumAssocs = Types.size(); |
| 1462 | assert(NumAssocs == Exprs.size()); |
| 1463 | |
| 1464 | // Decay and strip qualifiers for the controlling expression type, and handle |
| 1465 | // placeholder type replacement. See committee discussion from WG14 DR423. |
| 1466 | { |
| 1467 | EnterExpressionEvaluationContext Unevaluated( |
| 1468 | *this, Sema::ExpressionEvaluationContext::Unevaluated); |
| 1469 | ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); |
| 1470 | if (R.isInvalid()) |
| 1471 | return ExprError(); |
| 1472 | ControllingExpr = R.get(); |
| 1473 | } |
| 1474 | |
| 1475 | // The controlling expression is an unevaluated operand, so side effects are |
| 1476 | // likely unintended. |
| 1477 | if (!inTemplateInstantiation() && |
| 1478 | ControllingExpr->HasSideEffects(Context, false)) |
| 1479 | Diag(ControllingExpr->getExprLoc(), |
| 1480 | diag::warn_side_effects_unevaluated_context); |
| 1481 | |
| 1482 | bool TypeErrorFound = false, |
| 1483 | IsResultDependent = ControllingExpr->isTypeDependent(), |
| 1484 | ContainsUnexpandedParameterPack |
| 1485 | = ControllingExpr->containsUnexpandedParameterPack(); |
| 1486 | |
| 1487 | for (unsigned i = 0; i < NumAssocs; ++i) { |
| 1488 | if (Exprs[i]->containsUnexpandedParameterPack()) |
| 1489 | ContainsUnexpandedParameterPack = true; |
| 1490 | |
| 1491 | if (Types[i]) { |
| 1492 | if (Types[i]->getType()->containsUnexpandedParameterPack()) |
| 1493 | ContainsUnexpandedParameterPack = true; |
| 1494 | |
| 1495 | if (Types[i]->getType()->isDependentType()) { |
| 1496 | IsResultDependent = true; |
| 1497 | } else { |
| 1498 | // C11 6.5.1.1p2 "The type name in a generic association shall specify a |
| 1499 | // complete object type other than a variably modified type." |
| 1500 | unsigned D = 0; |
| 1501 | if (Types[i]->getType()->isIncompleteType()) |
| 1502 | D = diag::err_assoc_type_incomplete; |
| 1503 | else if (!Types[i]->getType()->isObjectType()) |
| 1504 | D = diag::err_assoc_type_nonobject; |
| 1505 | else if (Types[i]->getType()->isVariablyModifiedType()) |
| 1506 | D = diag::err_assoc_type_variably_modified; |
| 1507 | |
| 1508 | if (D != 0) { |
| 1509 | Diag(Types[i]->getTypeLoc().getBeginLoc(), D) |
| 1510 | << Types[i]->getTypeLoc().getSourceRange() |
| 1511 | << Types[i]->getType(); |
| 1512 | TypeErrorFound = true; |
| 1513 | } |
| 1514 | |
| 1515 | // C11 6.5.1.1p2 "No two generic associations in the same generic |
| 1516 | // selection shall specify compatible types." |
| 1517 | for (unsigned j = i+1; j < NumAssocs; ++j) |
| 1518 | if (Types[j] && !Types[j]->getType()->isDependentType() && |
| 1519 | Context.typesAreCompatible(Types[i]->getType(), |
| 1520 | Types[j]->getType())) { |
| 1521 | Diag(Types[j]->getTypeLoc().getBeginLoc(), |
| 1522 | diag::err_assoc_compatible_types) |
| 1523 | << Types[j]->getTypeLoc().getSourceRange() |
| 1524 | << Types[j]->getType() |
| 1525 | << Types[i]->getType(); |
| 1526 | Diag(Types[i]->getTypeLoc().getBeginLoc(), |
| 1527 | diag::note_compat_assoc) |
| 1528 | << Types[i]->getTypeLoc().getSourceRange() |
| 1529 | << Types[i]->getType(); |
| 1530 | TypeErrorFound = true; |
| 1531 | } |
| 1532 | } |
| 1533 | } |
| 1534 | } |
| 1535 | if (TypeErrorFound) |
| 1536 | return ExprError(); |
| 1537 | |
| 1538 | // If we determined that the generic selection is result-dependent, don't |
| 1539 | // try to compute the result expression. |
| 1540 | if (IsResultDependent) |
| 1541 | return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, |
| 1542 | Exprs, DefaultLoc, RParenLoc, |
| 1543 | ContainsUnexpandedParameterPack); |
| 1544 | |
| 1545 | SmallVector<unsigned, 1> CompatIndices; |
| 1546 | unsigned DefaultIndex = -1U; |
| 1547 | for (unsigned i = 0; i < NumAssocs; ++i) { |
| 1548 | if (!Types[i]) |
| 1549 | DefaultIndex = i; |
| 1550 | else if (Context.typesAreCompatible(ControllingExpr->getType(), |
| 1551 | Types[i]->getType())) |
| 1552 | CompatIndices.push_back(i); |
| 1553 | } |
| 1554 | |
| 1555 | // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have |
| 1556 | // type compatible with at most one of the types named in its generic |
| 1557 | // association list." |
| 1558 | if (CompatIndices.size() > 1) { |
| 1559 | // We strip parens here because the controlling expression is typically |
| 1560 | // parenthesized in macro definitions. |
| 1561 | ControllingExpr = ControllingExpr->IgnoreParens(); |
| 1562 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) |
| 1563 | << ControllingExpr->getSourceRange() << ControllingExpr->getType() |
| 1564 | << (unsigned)CompatIndices.size(); |
| 1565 | for (unsigned I : CompatIndices) { |
| 1566 | Diag(Types[I]->getTypeLoc().getBeginLoc(), |
| 1567 | diag::note_compat_assoc) |
| 1568 | << Types[I]->getTypeLoc().getSourceRange() |
| 1569 | << Types[I]->getType(); |
| 1570 | } |
| 1571 | return ExprError(); |
| 1572 | } |
| 1573 | |
| 1574 | // C11 6.5.1.1p2 "If a generic selection has no default generic association, |
| 1575 | // its controlling expression shall have type compatible with exactly one of |
| 1576 | // the types named in its generic association list." |
| 1577 | if (DefaultIndex == -1U && CompatIndices.size() == 0) { |
| 1578 | // We strip parens here because the controlling expression is typically |
| 1579 | // parenthesized in macro definitions. |
| 1580 | ControllingExpr = ControllingExpr->IgnoreParens(); |
| 1581 | Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) |
| 1582 | << ControllingExpr->getSourceRange() << ControllingExpr->getType(); |
| 1583 | return ExprError(); |
| 1584 | } |
| 1585 | |
| 1586 | // C11 6.5.1.1p3 "If a generic selection has a generic association with a |
| 1587 | // type name that is compatible with the type of the controlling expression, |
| 1588 | // then the result expression of the generic selection is the expression |
| 1589 | // in that generic association. Otherwise, the result expression of the |
| 1590 | // generic selection is the expression in the default generic association." |
| 1591 | unsigned ResultIndex = |
| 1592 | CompatIndices.size() ? CompatIndices[0] : DefaultIndex; |
| 1593 | |
| 1594 | return GenericSelectionExpr::Create( |
| 1595 | Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, |
| 1596 | ContainsUnexpandedParameterPack, ResultIndex); |
| 1597 | } |
| 1598 | |
| 1599 | /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the |
| 1600 | /// location of the token and the offset of the ud-suffix within it. |
| 1601 | static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, |
| 1602 | unsigned Offset) { |
| 1603 | return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), |
| 1604 | S.getLangOpts()); |
| 1605 | } |
| 1606 | |
| 1607 | /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up |
| 1608 | /// the corresponding cooked (non-raw) literal operator, and build a call to it. |
| 1609 | static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, |
| 1610 | IdentifierInfo *UDSuffix, |
| 1611 | SourceLocation UDSuffixLoc, |
| 1612 | ArrayRef<Expr*> Args, |
| 1613 | SourceLocation LitEndLoc) { |
| 1614 | assert(Args.size() <= 2 && "too many arguments for literal operator" ); |
| 1615 | |
| 1616 | QualType ArgTy[2]; |
| 1617 | for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { |
| 1618 | ArgTy[ArgIdx] = Args[ArgIdx]->getType(); |
| 1619 | if (ArgTy[ArgIdx]->isArrayType()) |
| 1620 | ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); |
| 1621 | } |
| 1622 | |
| 1623 | DeclarationName OpName = |
| 1624 | S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); |
| 1625 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
| 1626 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
| 1627 | |
| 1628 | LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); |
| 1629 | if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), |
| 1630 | /*AllowRaw*/ false, /*AllowTemplate*/ false, |
| 1631 | /*AllowStringTemplate*/ false, |
| 1632 | /*DiagnoseMissing*/ true) == Sema::LOLR_Error) |
| 1633 | return ExprError(); |
| 1634 | |
| 1635 | return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); |
| 1636 | } |
| 1637 | |
| 1638 | /// ActOnStringLiteral - The specified tokens were lexed as pasted string |
| 1639 | /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string |
| 1640 | /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from |
| 1641 | /// multiple tokens. However, the common case is that StringToks points to one |
| 1642 | /// string. |
| 1643 | /// |
| 1644 | ExprResult |
| 1645 | Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { |
| 1646 | assert(!StringToks.empty() && "Must have at least one string!" ); |
| 1647 | |
| 1648 | StringLiteralParser Literal(StringToks, PP); |
| 1649 | if (Literal.hadError) |
| 1650 | return ExprError(); |
| 1651 | |
| 1652 | SmallVector<SourceLocation, 4> StringTokLocs; |
| 1653 | for (const Token &Tok : StringToks) |
| 1654 | StringTokLocs.push_back(Tok.getLocation()); |
| 1655 | |
| 1656 | QualType CharTy = Context.CharTy; |
| 1657 | StringLiteral::StringKind Kind = StringLiteral::Ascii; |
| 1658 | if (Literal.isWide()) { |
| 1659 | CharTy = Context.getWideCharType(); |
| 1660 | Kind = StringLiteral::Wide; |
| 1661 | } else if (Literal.isUTF8()) { |
| 1662 | if (getLangOpts().Char8) |
| 1663 | CharTy = Context.Char8Ty; |
| 1664 | Kind = StringLiteral::UTF8; |
| 1665 | } else if (Literal.isUTF16()) { |
| 1666 | CharTy = Context.Char16Ty; |
| 1667 | Kind = StringLiteral::UTF16; |
| 1668 | } else if (Literal.isUTF32()) { |
| 1669 | CharTy = Context.Char32Ty; |
| 1670 | Kind = StringLiteral::UTF32; |
| 1671 | } else if (Literal.isPascal()) { |
| 1672 | CharTy = Context.UnsignedCharTy; |
| 1673 | } |
| 1674 | |
| 1675 | // Warn on initializing an array of char from a u8 string literal; this |
| 1676 | // becomes ill-formed in C++2a. |
| 1677 | if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && |
| 1678 | !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { |
| 1679 | Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); |
| 1680 | |
| 1681 | // Create removals for all 'u8' prefixes in the string literal(s). This |
| 1682 | // ensures C++2a compatibility (but may change the program behavior when |
| 1683 | // built by non-Clang compilers for which the execution character set is |
| 1684 | // not always UTF-8). |
| 1685 | auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); |
| 1686 | SourceLocation RemovalDiagLoc; |
| 1687 | for (const Token &Tok : StringToks) { |
| 1688 | if (Tok.getKind() == tok::utf8_string_literal) { |
| 1689 | if (RemovalDiagLoc.isInvalid()) |
| 1690 | RemovalDiagLoc = Tok.getLocation(); |
| 1691 | RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( |
| 1692 | Tok.getLocation(), |
| 1693 | Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, |
| 1694 | getSourceManager(), getLangOpts()))); |
| 1695 | } |
| 1696 | } |
| 1697 | Diag(RemovalDiagLoc, RemovalDiag); |
| 1698 | } |
| 1699 | |
| 1700 | QualType StrTy = |
| 1701 | Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); |
| 1702 | |
| 1703 | // Pass &StringTokLocs[0], StringTokLocs.size() to factory! |
| 1704 | StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), |
| 1705 | Kind, Literal.Pascal, StrTy, |
| 1706 | &StringTokLocs[0], |
| 1707 | StringTokLocs.size()); |
| 1708 | if (Literal.getUDSuffix().empty()) |
| 1709 | return Lit; |
| 1710 | |
| 1711 | // We're building a user-defined literal. |
| 1712 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); |
| 1713 | SourceLocation UDSuffixLoc = |
| 1714 | getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], |
| 1715 | Literal.getUDSuffixOffset()); |
| 1716 | |
| 1717 | // Make sure we're allowed user-defined literals here. |
| 1718 | if (!UDLScope) |
| 1719 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); |
| 1720 | |
| 1721 | // C++11 [lex.ext]p5: The literal L is treated as a call of the form |
| 1722 | // operator "" X (str, len) |
| 1723 | QualType SizeType = Context.getSizeType(); |
| 1724 | |
| 1725 | DeclarationName OpName = |
| 1726 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); |
| 1727 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
| 1728 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
| 1729 | |
| 1730 | QualType ArgTy[] = { |
| 1731 | Context.getArrayDecayedType(StrTy), SizeType |
| 1732 | }; |
| 1733 | |
| 1734 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
| 1735 | switch (LookupLiteralOperator(UDLScope, R, ArgTy, |
| 1736 | /*AllowRaw*/ false, /*AllowTemplate*/ false, |
| 1737 | /*AllowStringTemplate*/ true, |
| 1738 | /*DiagnoseMissing*/ true)) { |
| 1739 | |
| 1740 | case LOLR_Cooked: { |
| 1741 | llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); |
| 1742 | IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, |
| 1743 | StringTokLocs[0]); |
| 1744 | Expr *Args[] = { Lit, LenArg }; |
| 1745 | |
| 1746 | return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); |
| 1747 | } |
| 1748 | |
| 1749 | case LOLR_StringTemplate: { |
| 1750 | TemplateArgumentListInfo ExplicitArgs; |
| 1751 | |
| 1752 | unsigned CharBits = Context.getIntWidth(CharTy); |
| 1753 | bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); |
| 1754 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
| 1755 | |
| 1756 | TemplateArgument TypeArg(CharTy); |
| 1757 | TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); |
| 1758 | ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); |
| 1759 | |
| 1760 | for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { |
| 1761 | Value = Lit->getCodeUnit(I); |
| 1762 | TemplateArgument Arg(Context, Value, CharTy); |
| 1763 | TemplateArgumentLocInfo ArgInfo; |
| 1764 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); |
| 1765 | } |
| 1766 | return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), |
| 1767 | &ExplicitArgs); |
| 1768 | } |
| 1769 | case LOLR_Raw: |
| 1770 | case LOLR_Template: |
| 1771 | case LOLR_ErrorNoDiagnostic: |
| 1772 | llvm_unreachable("unexpected literal operator lookup result" ); |
| 1773 | case LOLR_Error: |
| 1774 | return ExprError(); |
| 1775 | } |
| 1776 | llvm_unreachable("unexpected literal operator lookup result" ); |
| 1777 | } |
| 1778 | |
| 1779 | DeclRefExpr * |
| 1780 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
| 1781 | SourceLocation Loc, |
| 1782 | const CXXScopeSpec *SS) { |
| 1783 | DeclarationNameInfo NameInfo(D->getDeclName(), Loc); |
| 1784 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); |
| 1785 | } |
| 1786 | |
| 1787 | DeclRefExpr * |
| 1788 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
| 1789 | const DeclarationNameInfo &NameInfo, |
| 1790 | const CXXScopeSpec *SS, NamedDecl *FoundD, |
| 1791 | SourceLocation TemplateKWLoc, |
| 1792 | const TemplateArgumentListInfo *TemplateArgs) { |
| 1793 | NestedNameSpecifierLoc NNS = |
| 1794 | SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); |
| 1795 | return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, |
| 1796 | TemplateArgs); |
| 1797 | } |
| 1798 | |
| 1799 | NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { |
| 1800 | // A declaration named in an unevaluated operand never constitutes an odr-use. |
| 1801 | if (isUnevaluatedContext()) |
| 1802 | return NOUR_Unevaluated; |
| 1803 | |
| 1804 | // C++2a [basic.def.odr]p4: |
| 1805 | // A variable x whose name appears as a potentially-evaluated expression e |
| 1806 | // is odr-used by e unless [...] x is a reference that is usable in |
| 1807 | // constant expressions. |
| 1808 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { |
| 1809 | if (VD->getType()->isReferenceType() && |
| 1810 | !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && |
| 1811 | VD->isUsableInConstantExpressions(Context)) |
| 1812 | return NOUR_Constant; |
| 1813 | } |
| 1814 | |
| 1815 | // All remaining non-variable cases constitute an odr-use. For variables, we |
| 1816 | // need to wait and see how the expression is used. |
| 1817 | return NOUR_None; |
| 1818 | } |
| 1819 | |
| 1820 | /// BuildDeclRefExpr - Build an expression that references a |
| 1821 | /// declaration that does not require a closure capture. |
| 1822 | DeclRefExpr * |
| 1823 | Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, |
| 1824 | const DeclarationNameInfo &NameInfo, |
| 1825 | NestedNameSpecifierLoc NNS, NamedDecl *FoundD, |
| 1826 | SourceLocation TemplateKWLoc, |
| 1827 | const TemplateArgumentListInfo *TemplateArgs) { |
| 1828 | bool RefersToCapturedVariable = |
| 1829 | isa<VarDecl>(D) && |
| 1830 | NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); |
| 1831 | |
| 1832 | DeclRefExpr *E = DeclRefExpr::Create( |
| 1833 | Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, |
| 1834 | VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); |
| 1835 | MarkDeclRefReferenced(E); |
| 1836 | |
| 1837 | if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && |
| 1838 | Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && |
| 1839 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) |
| 1840 | getCurFunction()->recordUseOfWeak(E); |
| 1841 | |
| 1842 | FieldDecl *FD = dyn_cast<FieldDecl>(D); |
| 1843 | if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) |
| 1844 | FD = IFD->getAnonField(); |
| 1845 | if (FD) { |
| 1846 | UnusedPrivateFields.remove(FD); |
| 1847 | // Just in case we're building an illegal pointer-to-member. |
| 1848 | if (FD->isBitField()) |
| 1849 | E->setObjectKind(OK_BitField); |
| 1850 | } |
| 1851 | |
| 1852 | // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier |
| 1853 | // designates a bit-field. |
| 1854 | if (auto *BD = dyn_cast<BindingDecl>(D)) |
| 1855 | if (auto *BE = BD->getBinding()) |
| 1856 | E->setObjectKind(BE->getObjectKind()); |
| 1857 | |
| 1858 | return E; |
| 1859 | } |
| 1860 | |
| 1861 | /// Decomposes the given name into a DeclarationNameInfo, its location, and |
| 1862 | /// possibly a list of template arguments. |
| 1863 | /// |
| 1864 | /// If this produces template arguments, it is permitted to call |
| 1865 | /// DecomposeTemplateName. |
| 1866 | /// |
| 1867 | /// This actually loses a lot of source location information for |
| 1868 | /// non-standard name kinds; we should consider preserving that in |
| 1869 | /// some way. |
| 1870 | void |
| 1871 | Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, |
| 1872 | TemplateArgumentListInfo &Buffer, |
| 1873 | DeclarationNameInfo &NameInfo, |
| 1874 | const TemplateArgumentListInfo *&TemplateArgs) { |
| 1875 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { |
| 1876 | Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); |
| 1877 | Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); |
| 1878 | |
| 1879 | ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), |
| 1880 | Id.TemplateId->NumArgs); |
| 1881 | translateTemplateArguments(TemplateArgsPtr, Buffer); |
| 1882 | |
| 1883 | TemplateName TName = Id.TemplateId->Template.get(); |
| 1884 | SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; |
| 1885 | NameInfo = Context.getNameForTemplate(TName, TNameLoc); |
| 1886 | TemplateArgs = &Buffer; |
| 1887 | } else { |
| 1888 | NameInfo = GetNameFromUnqualifiedId(Id); |
| 1889 | TemplateArgs = nullptr; |
| 1890 | } |
| 1891 | } |
| 1892 | |
| 1893 | static void emitEmptyLookupTypoDiagnostic( |
| 1894 | const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, |
| 1895 | DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, |
| 1896 | unsigned DiagnosticID, unsigned DiagnosticSuggestID) { |
| 1897 | DeclContext *Ctx = |
| 1898 | SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); |
| 1899 | if (!TC) { |
| 1900 | // Emit a special diagnostic for failed member lookups. |
| 1901 | // FIXME: computing the declaration context might fail here (?) |
| 1902 | if (Ctx) |
| 1903 | SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx |
| 1904 | << SS.getRange(); |
| 1905 | else |
| 1906 | SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; |
| 1907 | return; |
| 1908 | } |
| 1909 | |
| 1910 | std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); |
| 1911 | bool DroppedSpecifier = |
| 1912 | TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; |
| 1913 | unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() |
| 1914 | ? diag::note_implicit_param_decl |
| 1915 | : diag::note_previous_decl; |
| 1916 | if (!Ctx) |
| 1917 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, |
| 1918 | SemaRef.PDiag(NoteID)); |
| 1919 | else |
| 1920 | SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) |
| 1921 | << Typo << Ctx << DroppedSpecifier |
| 1922 | << SS.getRange(), |
| 1923 | SemaRef.PDiag(NoteID)); |
| 1924 | } |
| 1925 | |
| 1926 | /// Diagnose an empty lookup. |
| 1927 | /// |
| 1928 | /// \return false if new lookup candidates were found |
| 1929 | bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, |
| 1930 | CorrectionCandidateCallback &CCC, |
| 1931 | TemplateArgumentListInfo *ExplicitTemplateArgs, |
| 1932 | ArrayRef<Expr *> Args, TypoExpr **Out) { |
| 1933 | DeclarationName Name = R.getLookupName(); |
| 1934 | |
| 1935 | unsigned diagnostic = diag::err_undeclared_var_use; |
| 1936 | unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; |
| 1937 | if (Name.getNameKind() == DeclarationName::CXXOperatorName || |
| 1938 | Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || |
| 1939 | Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { |
| 1940 | diagnostic = diag::err_undeclared_use; |
| 1941 | diagnostic_suggest = diag::err_undeclared_use_suggest; |
| 1942 | } |
| 1943 | |
| 1944 | // If the original lookup was an unqualified lookup, fake an |
| 1945 | // unqualified lookup. This is useful when (for example) the |
| 1946 | // original lookup would not have found something because it was a |
| 1947 | // dependent name. |
| 1948 | DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; |
| 1949 | while (DC) { |
| 1950 | if (isa<CXXRecordDecl>(DC)) { |
| 1951 | LookupQualifiedName(R, DC); |
| 1952 | |
| 1953 | if (!R.empty()) { |
| 1954 | // Don't give errors about ambiguities in this lookup. |
| 1955 | R.suppressDiagnostics(); |
| 1956 | |
| 1957 | // During a default argument instantiation the CurContext points |
| 1958 | // to a CXXMethodDecl; but we can't apply a this-> fixit inside a |
| 1959 | // function parameter list, hence add an explicit check. |
| 1960 | bool isDefaultArgument = |
| 1961 | !CodeSynthesisContexts.empty() && |
| 1962 | CodeSynthesisContexts.back().Kind == |
| 1963 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation; |
| 1964 | CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); |
| 1965 | bool isInstance = CurMethod && |
| 1966 | CurMethod->isInstance() && |
| 1967 | DC == CurMethod->getParent() && !isDefaultArgument; |
| 1968 | |
| 1969 | // Give a code modification hint to insert 'this->'. |
| 1970 | // TODO: fixit for inserting 'Base<T>::' in the other cases. |
| 1971 | // Actually quite difficult! |
| 1972 | if (getLangOpts().MSVCCompat) |
| 1973 | diagnostic = diag::ext_found_via_dependent_bases_lookup; |
| 1974 | if (isInstance) { |
| 1975 | Diag(R.getNameLoc(), diagnostic) << Name |
| 1976 | << FixItHint::CreateInsertion(R.getNameLoc(), "this->" ); |
| 1977 | CheckCXXThisCapture(R.getNameLoc()); |
| 1978 | } else { |
| 1979 | Diag(R.getNameLoc(), diagnostic) << Name; |
| 1980 | } |
| 1981 | |
| 1982 | // Do we really want to note all of these? |
| 1983 | for (NamedDecl *D : R) |
| 1984 | Diag(D->getLocation(), diag::note_dependent_var_use); |
| 1985 | |
| 1986 | // Return true if we are inside a default argument instantiation |
| 1987 | // and the found name refers to an instance member function, otherwise |
| 1988 | // the function calling DiagnoseEmptyLookup will try to create an |
| 1989 | // implicit member call and this is wrong for default argument. |
| 1990 | if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { |
| 1991 | Diag(R.getNameLoc(), diag::err_member_call_without_object); |
| 1992 | return true; |
| 1993 | } |
| 1994 | |
| 1995 | // Tell the callee to try to recover. |
| 1996 | return false; |
| 1997 | } |
| 1998 | |
| 1999 | R.clear(); |
| 2000 | } |
| 2001 | |
| 2002 | // In Microsoft mode, if we are performing lookup from within a friend |
| 2003 | // function definition declared at class scope then we must set |
| 2004 | // DC to the lexical parent to be able to search into the parent |
| 2005 | // class. |
| 2006 | if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && |
| 2007 | cast<FunctionDecl>(DC)->getFriendObjectKind() && |
| 2008 | DC->getLexicalParent()->isRecord()) |
| 2009 | DC = DC->getLexicalParent(); |
| 2010 | else |
| 2011 | DC = DC->getParent(); |
| 2012 | } |
| 2013 | |
| 2014 | // We didn't find anything, so try to correct for a typo. |
| 2015 | TypoCorrection Corrected; |
| 2016 | if (S && Out) { |
| 2017 | SourceLocation TypoLoc = R.getNameLoc(); |
| 2018 | assert(!ExplicitTemplateArgs && |
| 2019 | "Diagnosing an empty lookup with explicit template args!" ); |
| 2020 | *Out = CorrectTypoDelayed( |
| 2021 | R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, |
| 2022 | [=](const TypoCorrection &TC) { |
| 2023 | emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, |
| 2024 | diagnostic, diagnostic_suggest); |
| 2025 | }, |
| 2026 | nullptr, CTK_ErrorRecovery); |
| 2027 | if (*Out) |
| 2028 | return true; |
| 2029 | } else if (S && |
| 2030 | (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), |
| 2031 | S, &SS, CCC, CTK_ErrorRecovery))) { |
| 2032 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
| 2033 | bool DroppedSpecifier = |
| 2034 | Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; |
| 2035 | R.setLookupName(Corrected.getCorrection()); |
| 2036 | |
| 2037 | bool AcceptableWithRecovery = false; |
| 2038 | bool AcceptableWithoutRecovery = false; |
| 2039 | NamedDecl *ND = Corrected.getFoundDecl(); |
| 2040 | if (ND) { |
| 2041 | if (Corrected.isOverloaded()) { |
| 2042 | OverloadCandidateSet OCS(R.getNameLoc(), |
| 2043 | OverloadCandidateSet::CSK_Normal); |
| 2044 | OverloadCandidateSet::iterator Best; |
| 2045 | for (NamedDecl *CD : Corrected) { |
| 2046 | if (FunctionTemplateDecl *FTD = |
| 2047 | dyn_cast<FunctionTemplateDecl>(CD)) |
| 2048 | AddTemplateOverloadCandidate( |
| 2049 | FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, |
| 2050 | Args, OCS); |
| 2051 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) |
| 2052 | if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) |
| 2053 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), |
| 2054 | Args, OCS); |
| 2055 | } |
| 2056 | switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { |
| 2057 | case OR_Success: |
| 2058 | ND = Best->FoundDecl; |
| 2059 | Corrected.setCorrectionDecl(ND); |
| 2060 | break; |
| 2061 | default: |
| 2062 | // FIXME: Arbitrarily pick the first declaration for the note. |
| 2063 | Corrected.setCorrectionDecl(ND); |
| 2064 | break; |
| 2065 | } |
| 2066 | } |
| 2067 | R.addDecl(ND); |
| 2068 | if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { |
| 2069 | CXXRecordDecl *Record = nullptr; |
| 2070 | if (Corrected.getCorrectionSpecifier()) { |
| 2071 | const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); |
| 2072 | Record = Ty->getAsCXXRecordDecl(); |
| 2073 | } |
| 2074 | if (!Record) |
| 2075 | Record = cast<CXXRecordDecl>( |
| 2076 | ND->getDeclContext()->getRedeclContext()); |
| 2077 | R.setNamingClass(Record); |
| 2078 | } |
| 2079 | |
| 2080 | auto *UnderlyingND = ND->getUnderlyingDecl(); |
| 2081 | AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || |
| 2082 | isa<FunctionTemplateDecl>(UnderlyingND); |
| 2083 | // FIXME: If we ended up with a typo for a type name or |
| 2084 | // Objective-C class name, we're in trouble because the parser |
| 2085 | // is in the wrong place to recover. Suggest the typo |
| 2086 | // correction, but don't make it a fix-it since we're not going |
| 2087 | // to recover well anyway. |
| 2088 | AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || |
| 2089 | getAsTypeTemplateDecl(UnderlyingND) || |
| 2090 | isa<ObjCInterfaceDecl>(UnderlyingND); |
| 2091 | } else { |
| 2092 | // FIXME: We found a keyword. Suggest it, but don't provide a fix-it |
| 2093 | // because we aren't able to recover. |
| 2094 | AcceptableWithoutRecovery = true; |
| 2095 | } |
| 2096 | |
| 2097 | if (AcceptableWithRecovery || AcceptableWithoutRecovery) { |
| 2098 | unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() |
| 2099 | ? diag::note_implicit_param_decl |
| 2100 | : diag::note_previous_decl; |
| 2101 | if (SS.isEmpty()) |
| 2102 | diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, |
| 2103 | PDiag(NoteID), AcceptableWithRecovery); |
| 2104 | else |
| 2105 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) |
| 2106 | << Name << computeDeclContext(SS, false) |
| 2107 | << DroppedSpecifier << SS.getRange(), |
| 2108 | PDiag(NoteID), AcceptableWithRecovery); |
| 2109 | |
| 2110 | // Tell the callee whether to try to recover. |
| 2111 | return !AcceptableWithRecovery; |
| 2112 | } |
| 2113 | } |
| 2114 | R.clear(); |
| 2115 | |
| 2116 | // Emit a special diagnostic for failed member lookups. |
| 2117 | // FIXME: computing the declaration context might fail here (?) |
| 2118 | if (!SS.isEmpty()) { |
| 2119 | Diag(R.getNameLoc(), diag::err_no_member) |
| 2120 | << Name << computeDeclContext(SS, false) |
| 2121 | << SS.getRange(); |
| 2122 | return true; |
| 2123 | } |
| 2124 | |
| 2125 | // Give up, we can't recover. |
| 2126 | Diag(R.getNameLoc(), diagnostic) << Name; |
| 2127 | return true; |
| 2128 | } |
| 2129 | |
| 2130 | /// In Microsoft mode, if we are inside a template class whose parent class has |
| 2131 | /// dependent base classes, and we can't resolve an unqualified identifier, then |
| 2132 | /// assume the identifier is a member of a dependent base class. We can only |
| 2133 | /// recover successfully in static methods, instance methods, and other contexts |
| 2134 | /// where 'this' is available. This doesn't precisely match MSVC's |
| 2135 | /// instantiation model, but it's close enough. |
| 2136 | static Expr * |
| 2137 | recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, |
| 2138 | DeclarationNameInfo &NameInfo, |
| 2139 | SourceLocation TemplateKWLoc, |
| 2140 | const TemplateArgumentListInfo *TemplateArgs) { |
| 2141 | // Only try to recover from lookup into dependent bases in static methods or |
| 2142 | // contexts where 'this' is available. |
| 2143 | QualType ThisType = S.getCurrentThisType(); |
| 2144 | const CXXRecordDecl *RD = nullptr; |
| 2145 | if (!ThisType.isNull()) |
| 2146 | RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); |
| 2147 | else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) |
| 2148 | RD = MD->getParent(); |
| 2149 | if (!RD || !RD->hasAnyDependentBases()) |
| 2150 | return nullptr; |
| 2151 | |
| 2152 | // Diagnose this as unqualified lookup into a dependent base class. If 'this' |
| 2153 | // is available, suggest inserting 'this->' as a fixit. |
| 2154 | SourceLocation Loc = NameInfo.getLoc(); |
| 2155 | auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); |
| 2156 | DB << NameInfo.getName() << RD; |
| 2157 | |
| 2158 | if (!ThisType.isNull()) { |
| 2159 | DB << FixItHint::CreateInsertion(Loc, "this->" ); |
| 2160 | return CXXDependentScopeMemberExpr::Create( |
| 2161 | Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, |
| 2162 | /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, |
| 2163 | /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); |
| 2164 | } |
| 2165 | |
| 2166 | // Synthesize a fake NNS that points to the derived class. This will |
| 2167 | // perform name lookup during template instantiation. |
| 2168 | CXXScopeSpec SS; |
| 2169 | auto *NNS = |
| 2170 | NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); |
| 2171 | SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); |
| 2172 | return DependentScopeDeclRefExpr::Create( |
| 2173 | Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, |
| 2174 | TemplateArgs); |
| 2175 | } |
| 2176 | |
| 2177 | ExprResult |
| 2178 | Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, |
| 2179 | SourceLocation TemplateKWLoc, UnqualifiedId &Id, |
| 2180 | bool HasTrailingLParen, bool IsAddressOfOperand, |
| 2181 | CorrectionCandidateCallback *CCC, |
| 2182 | bool IsInlineAsmIdentifier, Token *KeywordReplacement) { |
| 2183 | assert(!(IsAddressOfOperand && HasTrailingLParen) && |
| 2184 | "cannot be direct & operand and have a trailing lparen" ); |
| 2185 | if (SS.isInvalid()) |
| 2186 | return ExprError(); |
| 2187 | |
| 2188 | TemplateArgumentListInfo TemplateArgsBuffer; |
| 2189 | |
| 2190 | // Decompose the UnqualifiedId into the following data. |
| 2191 | DeclarationNameInfo NameInfo; |
| 2192 | const TemplateArgumentListInfo *TemplateArgs; |
| 2193 | DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); |
| 2194 | |
| 2195 | DeclarationName Name = NameInfo.getName(); |
| 2196 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
| 2197 | SourceLocation NameLoc = NameInfo.getLoc(); |
| 2198 | |
| 2199 | if (II && II->isEditorPlaceholder()) { |
| 2200 | // FIXME: When typed placeholders are supported we can create a typed |
| 2201 | // placeholder expression node. |
| 2202 | return ExprError(); |
| 2203 | } |
| 2204 | |
| 2205 | // C++ [temp.dep.expr]p3: |
| 2206 | // An id-expression is type-dependent if it contains: |
| 2207 | // -- an identifier that was declared with a dependent type, |
| 2208 | // (note: handled after lookup) |
| 2209 | // -- a template-id that is dependent, |
| 2210 | // (note: handled in BuildTemplateIdExpr) |
| 2211 | // -- a conversion-function-id that specifies a dependent type, |
| 2212 | // -- a nested-name-specifier that contains a class-name that |
| 2213 | // names a dependent type. |
| 2214 | // Determine whether this is a member of an unknown specialization; |
| 2215 | // we need to handle these differently. |
| 2216 | bool DependentID = false; |
| 2217 | if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && |
| 2218 | Name.getCXXNameType()->isDependentType()) { |
| 2219 | DependentID = true; |
| 2220 | } else if (SS.isSet()) { |
| 2221 | if (DeclContext *DC = computeDeclContext(SS, false)) { |
| 2222 | if (RequireCompleteDeclContext(SS, DC)) |
| 2223 | return ExprError(); |
| 2224 | } else { |
| 2225 | DependentID = true; |
| 2226 | } |
| 2227 | } |
| 2228 | |
| 2229 | if (DependentID) |
| 2230 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
| 2231 | IsAddressOfOperand, TemplateArgs); |
| 2232 | |
| 2233 | // Perform the required lookup. |
| 2234 | LookupResult R(*this, NameInfo, |
| 2235 | (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) |
| 2236 | ? LookupObjCImplicitSelfParam |
| 2237 | : LookupOrdinaryName); |
| 2238 | if (TemplateKWLoc.isValid() || TemplateArgs) { |
| 2239 | // Lookup the template name again to correctly establish the context in |
| 2240 | // which it was found. This is really unfortunate as we already did the |
| 2241 | // lookup to determine that it was a template name in the first place. If |
| 2242 | // this becomes a performance hit, we can work harder to preserve those |
| 2243 | // results until we get here but it's likely not worth it. |
| 2244 | bool MemberOfUnknownSpecialization; |
| 2245 | AssumedTemplateKind AssumedTemplate; |
| 2246 | if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, |
| 2247 | MemberOfUnknownSpecialization, TemplateKWLoc, |
| 2248 | &AssumedTemplate)) |
| 2249 | return ExprError(); |
| 2250 | |
| 2251 | if (MemberOfUnknownSpecialization || |
| 2252 | (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) |
| 2253 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
| 2254 | IsAddressOfOperand, TemplateArgs); |
| 2255 | } else { |
| 2256 | bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); |
| 2257 | LookupParsedName(R, S, &SS, !IvarLookupFollowUp); |
| 2258 | |
| 2259 | // If the result might be in a dependent base class, this is a dependent |
| 2260 | // id-expression. |
| 2261 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) |
| 2262 | return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, |
| 2263 | IsAddressOfOperand, TemplateArgs); |
| 2264 | |
| 2265 | // If this reference is in an Objective-C method, then we need to do |
| 2266 | // some special Objective-C lookup, too. |
| 2267 | if (IvarLookupFollowUp) { |
| 2268 | ExprResult E(LookupInObjCMethod(R, S, II, true)); |
| 2269 | if (E.isInvalid()) |
| 2270 | return ExprError(); |
| 2271 | |
| 2272 | if (Expr *Ex = E.getAs<Expr>()) |
| 2273 | return Ex; |
| 2274 | } |
| 2275 | } |
| 2276 | |
| 2277 | if (R.isAmbiguous()) |
| 2278 | return ExprError(); |
| 2279 | |
| 2280 | // This could be an implicitly declared function reference (legal in C90, |
| 2281 | // extension in C99, forbidden in C++). |
| 2282 | if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { |
| 2283 | NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); |
| 2284 | if (D) R.addDecl(D); |
| 2285 | } |
| 2286 | |
| 2287 | // Determine whether this name might be a candidate for |
| 2288 | // argument-dependent lookup. |
| 2289 | bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); |
| 2290 | |
| 2291 | if (R.empty() && !ADL) { |
| 2292 | if (SS.isEmpty() && getLangOpts().MSVCCompat) { |
| 2293 | if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, |
| 2294 | TemplateKWLoc, TemplateArgs)) |
| 2295 | return E; |
| 2296 | } |
| 2297 | |
| 2298 | // Don't diagnose an empty lookup for inline assembly. |
| 2299 | if (IsInlineAsmIdentifier) |
| 2300 | return ExprError(); |
| 2301 | |
| 2302 | // If this name wasn't predeclared and if this is not a function |
| 2303 | // call, diagnose the problem. |
| 2304 | TypoExpr *TE = nullptr; |
| 2305 | DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() |
| 2306 | : nullptr); |
| 2307 | DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; |
| 2308 | assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && |
| 2309 | "Typo correction callback misconfigured" ); |
| 2310 | if (CCC) { |
| 2311 | // Make sure the callback knows what the typo being diagnosed is. |
| 2312 | CCC->setTypoName(II); |
| 2313 | if (SS.isValid()) |
| 2314 | CCC->setTypoNNS(SS.getScopeRep()); |
| 2315 | } |
| 2316 | // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for |
| 2317 | // a template name, but we happen to have always already looked up the name |
| 2318 | // before we get here if it must be a template name. |
| 2319 | if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, |
| 2320 | None, &TE)) { |
| 2321 | if (TE && KeywordReplacement) { |
| 2322 | auto &State = getTypoExprState(TE); |
| 2323 | auto BestTC = State.Consumer->getNextCorrection(); |
| 2324 | if (BestTC.isKeyword()) { |
| 2325 | auto *II = BestTC.getCorrectionAsIdentifierInfo(); |
| 2326 | if (State.DiagHandler) |
| 2327 | State.DiagHandler(BestTC); |
| 2328 | KeywordReplacement->startToken(); |
| 2329 | KeywordReplacement->setKind(II->getTokenID()); |
| 2330 | KeywordReplacement->setIdentifierInfo(II); |
| 2331 | KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); |
| 2332 | // Clean up the state associated with the TypoExpr, since it has |
| 2333 | // now been diagnosed (without a call to CorrectDelayedTyposInExpr). |
| 2334 | clearDelayedTypo(TE); |
| 2335 | // Signal that a correction to a keyword was performed by returning a |
| 2336 | // valid-but-null ExprResult. |
| 2337 | return (Expr*)nullptr; |
| 2338 | } |
| 2339 | State.Consumer->resetCorrectionStream(); |
| 2340 | } |
| 2341 | return TE ? TE : ExprError(); |
| 2342 | } |
| 2343 | |
| 2344 | assert(!R.empty() && |
| 2345 | "DiagnoseEmptyLookup returned false but added no results" ); |
| 2346 | |
| 2347 | // If we found an Objective-C instance variable, let |
| 2348 | // LookupInObjCMethod build the appropriate expression to |
| 2349 | // reference the ivar. |
| 2350 | if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { |
| 2351 | R.clear(); |
| 2352 | ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); |
| 2353 | // In a hopelessly buggy code, Objective-C instance variable |
| 2354 | // lookup fails and no expression will be built to reference it. |
| 2355 | if (!E.isInvalid() && !E.get()) |
| 2356 | return ExprError(); |
| 2357 | return E; |
| 2358 | } |
| 2359 | } |
| 2360 | |
| 2361 | // This is guaranteed from this point on. |
| 2362 | assert(!R.empty() || ADL); |
| 2363 | |
| 2364 | // Check whether this might be a C++ implicit instance member access. |
| 2365 | // C++ [class.mfct.non-static]p3: |
| 2366 | // When an id-expression that is not part of a class member access |
| 2367 | // syntax and not used to form a pointer to member is used in the |
| 2368 | // body of a non-static member function of class X, if name lookup |
| 2369 | // resolves the name in the id-expression to a non-static non-type |
| 2370 | // member of some class C, the id-expression is transformed into a |
| 2371 | // class member access expression using (*this) as the |
| 2372 | // postfix-expression to the left of the . operator. |
| 2373 | // |
| 2374 | // But we don't actually need to do this for '&' operands if R |
| 2375 | // resolved to a function or overloaded function set, because the |
| 2376 | // expression is ill-formed if it actually works out to be a |
| 2377 | // non-static member function: |
| 2378 | // |
| 2379 | // C++ [expr.ref]p4: |
| 2380 | // Otherwise, if E1.E2 refers to a non-static member function. . . |
| 2381 | // [t]he expression can be used only as the left-hand operand of a |
| 2382 | // member function call. |
| 2383 | // |
| 2384 | // There are other safeguards against such uses, but it's important |
| 2385 | // to get this right here so that we don't end up making a |
| 2386 | // spuriously dependent expression if we're inside a dependent |
| 2387 | // instance method. |
| 2388 | if (!R.empty() && (*R.begin())->isCXXClassMember()) { |
| 2389 | bool MightBeImplicitMember; |
| 2390 | if (!IsAddressOfOperand) |
| 2391 | MightBeImplicitMember = true; |
| 2392 | else if (!SS.isEmpty()) |
| 2393 | MightBeImplicitMember = false; |
| 2394 | else if (R.isOverloadedResult()) |
| 2395 | MightBeImplicitMember = false; |
| 2396 | else if (R.isUnresolvableResult()) |
| 2397 | MightBeImplicitMember = true; |
| 2398 | else |
| 2399 | MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || |
| 2400 | isa<IndirectFieldDecl>(R.getFoundDecl()) || |
| 2401 | isa<MSPropertyDecl>(R.getFoundDecl()); |
| 2402 | |
| 2403 | if (MightBeImplicitMember) |
| 2404 | return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, |
| 2405 | R, TemplateArgs, S); |
| 2406 | } |
| 2407 | |
| 2408 | if (TemplateArgs || TemplateKWLoc.isValid()) { |
| 2409 | |
| 2410 | // In C++1y, if this is a variable template id, then check it |
| 2411 | // in BuildTemplateIdExpr(). |
| 2412 | // The single lookup result must be a variable template declaration. |
| 2413 | if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && |
| 2414 | Id.TemplateId->Kind == TNK_Var_template) { |
| 2415 | assert(R.getAsSingle<VarTemplateDecl>() && |
| 2416 | "There should only be one declaration found." ); |
| 2417 | } |
| 2418 | |
| 2419 | return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); |
| 2420 | } |
| 2421 | |
| 2422 | return BuildDeclarationNameExpr(SS, R, ADL); |
| 2423 | } |
| 2424 | |
| 2425 | /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified |
| 2426 | /// declaration name, generally during template instantiation. |
| 2427 | /// There's a large number of things which don't need to be done along |
| 2428 | /// this path. |
| 2429 | ExprResult Sema::BuildQualifiedDeclarationNameExpr( |
| 2430 | CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, |
| 2431 | bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { |
| 2432 | DeclContext *DC = computeDeclContext(SS, false); |
| 2433 | if (!DC) |
| 2434 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), |
| 2435 | NameInfo, /*TemplateArgs=*/nullptr); |
| 2436 | |
| 2437 | if (RequireCompleteDeclContext(SS, DC)) |
| 2438 | return ExprError(); |
| 2439 | |
| 2440 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
| 2441 | LookupQualifiedName(R, DC); |
| 2442 | |
| 2443 | if (R.isAmbiguous()) |
| 2444 | return ExprError(); |
| 2445 | |
| 2446 | if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) |
| 2447 | return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), |
| 2448 | NameInfo, /*TemplateArgs=*/nullptr); |
| 2449 | |
| 2450 | if (R.empty()) { |
| 2451 | Diag(NameInfo.getLoc(), diag::err_no_member) |
| 2452 | << NameInfo.getName() << DC << SS.getRange(); |
| 2453 | return ExprError(); |
| 2454 | } |
| 2455 | |
| 2456 | if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { |
| 2457 | // Diagnose a missing typename if this resolved unambiguously to a type in |
| 2458 | // a dependent context. If we can recover with a type, downgrade this to |
| 2459 | // a warning in Microsoft compatibility mode. |
| 2460 | unsigned DiagID = diag::err_typename_missing; |
| 2461 | if (RecoveryTSI && getLangOpts().MSVCCompat) |
| 2462 | DiagID = diag::ext_typename_missing; |
| 2463 | SourceLocation Loc = SS.getBeginLoc(); |
| 2464 | auto D = Diag(Loc, DiagID); |
| 2465 | D << SS.getScopeRep() << NameInfo.getName().getAsString() |
| 2466 | << SourceRange(Loc, NameInfo.getEndLoc()); |
| 2467 | |
| 2468 | // Don't recover if the caller isn't expecting us to or if we're in a SFINAE |
| 2469 | // context. |
| 2470 | if (!RecoveryTSI) |
| 2471 | return ExprError(); |
| 2472 | |
| 2473 | // Only issue the fixit if we're prepared to recover. |
| 2474 | D << FixItHint::CreateInsertion(Loc, "typename " ); |
| 2475 | |
| 2476 | // Recover by pretending this was an elaborated type. |
| 2477 | QualType Ty = Context.getTypeDeclType(TD); |
| 2478 | TypeLocBuilder TLB; |
| 2479 | TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); |
| 2480 | |
| 2481 | QualType ET = getElaboratedType(ETK_None, SS, Ty); |
| 2482 | ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); |
| 2483 | QTL.setElaboratedKeywordLoc(SourceLocation()); |
| 2484 | QTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| 2485 | |
| 2486 | *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); |
| 2487 | |
| 2488 | return ExprEmpty(); |
| 2489 | } |
| 2490 | |
| 2491 | // Defend against this resolving to an implicit member access. We usually |
| 2492 | // won't get here if this might be a legitimate a class member (we end up in |
| 2493 | // BuildMemberReferenceExpr instead), but this can be valid if we're forming |
| 2494 | // a pointer-to-member or in an unevaluated context in C++11. |
| 2495 | if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) |
| 2496 | return BuildPossibleImplicitMemberExpr(SS, |
| 2497 | /*TemplateKWLoc=*/SourceLocation(), |
| 2498 | R, /*TemplateArgs=*/nullptr, S); |
| 2499 | |
| 2500 | return BuildDeclarationNameExpr(SS, R, /* ADL */ false); |
| 2501 | } |
| 2502 | |
| 2503 | /// LookupInObjCMethod - The parser has read a name in, and Sema has |
| 2504 | /// detected that we're currently inside an ObjC method. Perform some |
| 2505 | /// additional lookup. |
| 2506 | /// |
| 2507 | /// Ideally, most of this would be done by lookup, but there's |
| 2508 | /// actually quite a lot of extra work involved. |
| 2509 | /// |
| 2510 | /// Returns a null sentinel to indicate trivial success. |
| 2511 | ExprResult |
| 2512 | Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, |
| 2513 | IdentifierInfo *II, bool AllowBuiltinCreation) { |
| 2514 | SourceLocation Loc = Lookup.getNameLoc(); |
| 2515 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); |
| 2516 | |
| 2517 | // Check for error condition which is already reported. |
| 2518 | if (!CurMethod) |
| 2519 | return ExprError(); |
| 2520 | |
| 2521 | // There are two cases to handle here. 1) scoped lookup could have failed, |
| 2522 | // in which case we should look for an ivar. 2) scoped lookup could have |
| 2523 | // found a decl, but that decl is outside the current instance method (i.e. |
| 2524 | // a global variable). In these two cases, we do a lookup for an ivar with |
| 2525 | // this name, if the lookup sucedes, we replace it our current decl. |
| 2526 | |
| 2527 | // If we're in a class method, we don't normally want to look for |
| 2528 | // ivars. But if we don't find anything else, and there's an |
| 2529 | // ivar, that's an error. |
| 2530 | bool IsClassMethod = CurMethod->isClassMethod(); |
| 2531 | |
| 2532 | bool LookForIvars; |
| 2533 | if (Lookup.empty()) |
| 2534 | LookForIvars = true; |
| 2535 | else if (IsClassMethod) |
| 2536 | LookForIvars = false; |
| 2537 | else |
| 2538 | LookForIvars = (Lookup.isSingleResult() && |
| 2539 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); |
| 2540 | ObjCInterfaceDecl *IFace = nullptr; |
| 2541 | if (LookForIvars) { |
| 2542 | IFace = CurMethod->getClassInterface(); |
| 2543 | ObjCInterfaceDecl *ClassDeclared; |
| 2544 | ObjCIvarDecl *IV = nullptr; |
| 2545 | if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { |
| 2546 | // Diagnose using an ivar in a class method. |
| 2547 | if (IsClassMethod) |
| 2548 | return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) |
| 2549 | << IV->getDeclName()); |
| 2550 | |
| 2551 | // If we're referencing an invalid decl, just return this as a silent |
| 2552 | // error node. The error diagnostic was already emitted on the decl. |
| 2553 | if (IV->isInvalidDecl()) |
| 2554 | return ExprError(); |
| 2555 | |
| 2556 | // Check if referencing a field with __attribute__((deprecated)). |
| 2557 | if (DiagnoseUseOfDecl(IV, Loc)) |
| 2558 | return ExprError(); |
| 2559 | |
| 2560 | // Diagnose the use of an ivar outside of the declaring class. |
| 2561 | if (IV->getAccessControl() == ObjCIvarDecl::Private && |
| 2562 | !declaresSameEntity(ClassDeclared, IFace) && |
| 2563 | !getLangOpts().DebuggerSupport) |
| 2564 | Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); |
| 2565 | |
| 2566 | // FIXME: This should use a new expr for a direct reference, don't |
| 2567 | // turn this into Self->ivar, just return a BareIVarExpr or something. |
| 2568 | IdentifierInfo &II = Context.Idents.get("self" ); |
| 2569 | UnqualifiedId SelfName; |
| 2570 | SelfName.setIdentifier(&II, SourceLocation()); |
| 2571 | SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); |
| 2572 | CXXScopeSpec SelfScopeSpec; |
| 2573 | SourceLocation TemplateKWLoc; |
| 2574 | ExprResult SelfExpr = |
| 2575 | ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, |
| 2576 | /*HasTrailingLParen=*/false, |
| 2577 | /*IsAddressOfOperand=*/false); |
| 2578 | if (SelfExpr.isInvalid()) |
| 2579 | return ExprError(); |
| 2580 | |
| 2581 | SelfExpr = DefaultLvalueConversion(SelfExpr.get()); |
| 2582 | if (SelfExpr.isInvalid()) |
| 2583 | return ExprError(); |
| 2584 | |
| 2585 | MarkAnyDeclReferenced(Loc, IV, true); |
| 2586 | |
| 2587 | ObjCMethodFamily MF = CurMethod->getMethodFamily(); |
| 2588 | if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && |
| 2589 | !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) |
| 2590 | Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); |
| 2591 | |
| 2592 | ObjCIvarRefExpr *Result = new (Context) |
| 2593 | ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, |
| 2594 | IV->getLocation(), SelfExpr.get(), true, true); |
| 2595 | |
| 2596 | if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { |
| 2597 | if (!isUnevaluatedContext() && |
| 2598 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) |
| 2599 | getCurFunction()->recordUseOfWeak(Result); |
| 2600 | } |
| 2601 | if (getLangOpts().ObjCAutoRefCount) |
| 2602 | if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) |
| 2603 | ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); |
| 2604 | |
| 2605 | return Result; |
| 2606 | } |
| 2607 | } else if (CurMethod->isInstanceMethod()) { |
| 2608 | // We should warn if a local variable hides an ivar. |
| 2609 | if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { |
| 2610 | ObjCInterfaceDecl *ClassDeclared; |
| 2611 | if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { |
| 2612 | if (IV->getAccessControl() != ObjCIvarDecl::Private || |
| 2613 | declaresSameEntity(IFace, ClassDeclared)) |
| 2614 | Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); |
| 2615 | } |
| 2616 | } |
| 2617 | } else if (Lookup.isSingleResult() && |
| 2618 | Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { |
| 2619 | // If accessing a stand-alone ivar in a class method, this is an error. |
| 2620 | if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) |
| 2621 | return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) |
| 2622 | << IV->getDeclName()); |
| 2623 | } |
| 2624 | |
| 2625 | if (Lookup.empty() && II && AllowBuiltinCreation) { |
| 2626 | // FIXME. Consolidate this with similar code in LookupName. |
| 2627 | if (unsigned BuiltinID = II->getBuiltinID()) { |
| 2628 | if (!(getLangOpts().CPlusPlus && |
| 2629 | Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { |
| 2630 | NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, |
| 2631 | S, Lookup.isForRedeclaration(), |
| 2632 | Lookup.getNameLoc()); |
| 2633 | if (D) Lookup.addDecl(D); |
| 2634 | } |
| 2635 | } |
| 2636 | } |
| 2637 | // Sentinel value saying that we didn't do anything special. |
| 2638 | return ExprResult((Expr *)nullptr); |
| 2639 | } |
| 2640 | |
| 2641 | /// Cast a base object to a member's actual type. |
| 2642 | /// |
| 2643 | /// Logically this happens in three phases: |
| 2644 | /// |
| 2645 | /// * First we cast from the base type to the naming class. |
| 2646 | /// The naming class is the class into which we were looking |
| 2647 | /// when we found the member; it's the qualifier type if a |
| 2648 | /// qualifier was provided, and otherwise it's the base type. |
| 2649 | /// |
| 2650 | /// * Next we cast from the naming class to the declaring class. |
| 2651 | /// If the member we found was brought into a class's scope by |
| 2652 | /// a using declaration, this is that class; otherwise it's |
| 2653 | /// the class declaring the member. |
| 2654 | /// |
| 2655 | /// * Finally we cast from the declaring class to the "true" |
| 2656 | /// declaring class of the member. This conversion does not |
| 2657 | /// obey access control. |
| 2658 | ExprResult |
| 2659 | Sema::PerformObjectMemberConversion(Expr *From, |
| 2660 | NestedNameSpecifier *Qualifier, |
| 2661 | NamedDecl *FoundDecl, |
| 2662 | NamedDecl *Member) { |
| 2663 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); |
| 2664 | if (!RD) |
| 2665 | return From; |
| 2666 | |
| 2667 | QualType DestRecordType; |
| 2668 | QualType DestType; |
| 2669 | QualType FromRecordType; |
| 2670 | QualType FromType = From->getType(); |
| 2671 | bool PointerConversions = false; |
| 2672 | if (isa<FieldDecl>(Member)) { |
| 2673 | DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); |
| 2674 | auto FromPtrType = FromType->getAs<PointerType>(); |
| 2675 | DestRecordType = Context.getAddrSpaceQualType( |
| 2676 | DestRecordType, FromPtrType |
| 2677 | ? FromType->getPointeeType().getAddressSpace() |
| 2678 | : FromType.getAddressSpace()); |
| 2679 | |
| 2680 | if (FromPtrType) { |
| 2681 | DestType = Context.getPointerType(DestRecordType, |
| 2682 | FromPtrType->isCHERICapability() |
| 2683 | ? ASTContext::PIK_Capability |
| 2684 | : ASTContext::PIK_Integer); |
| 2685 | FromRecordType = FromPtrType->getPointeeType(); |
| 2686 | PointerConversions = true; |
| 2687 | } else { |
| 2688 | DestType = DestRecordType; |
| 2689 | FromRecordType = FromType; |
| 2690 | } |
| 2691 | } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { |
| 2692 | if (Method->isStatic()) |
| 2693 | return From; |
| 2694 | |
| 2695 | DestType = Method->getThisType(); |
| 2696 | DestRecordType = DestType->getPointeeType(); |
| 2697 | |
| 2698 | if (FromType->getAs<PointerType>()) { |
| 2699 | FromRecordType = FromType->getPointeeType(); |
| 2700 | PointerConversions = true; |
| 2701 | } else { |
| 2702 | FromRecordType = FromType; |
| 2703 | DestType = DestRecordType; |
| 2704 | } |
| 2705 | } else { |
| 2706 | // No conversion necessary. |
| 2707 | return From; |
| 2708 | } |
| 2709 | |
| 2710 | if (DestType->isDependentType() || FromType->isDependentType()) |
| 2711 | return From; |
| 2712 | |
| 2713 | // If the unqualified types are the same, no conversion is necessary. |
| 2714 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) |
| 2715 | return From; |
| 2716 | |
| 2717 | SourceRange FromRange = From->getSourceRange(); |
| 2718 | SourceLocation FromLoc = FromRange.getBegin(); |
| 2719 | |
| 2720 | ExprValueKind VK = From->getValueKind(); |
| 2721 | |
| 2722 | // C++ [class.member.lookup]p8: |
| 2723 | // [...] Ambiguities can often be resolved by qualifying a name with its |
| 2724 | // class name. |
| 2725 | // |
| 2726 | // If the member was a qualified name and the qualified referred to a |
| 2727 | // specific base subobject type, we'll cast to that intermediate type |
| 2728 | // first and then to the object in which the member is declared. That allows |
| 2729 | // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: |
| 2730 | // |
| 2731 | // class Base { public: int x; }; |
| 2732 | // class Derived1 : public Base { }; |
| 2733 | // class Derived2 : public Base { }; |
| 2734 | // class VeryDerived : public Derived1, public Derived2 { void f(); }; |
| 2735 | // |
| 2736 | // void VeryDerived::f() { |
| 2737 | // x = 17; // error: ambiguous base subobjects |
| 2738 | // Derived1::x = 17; // okay, pick the Base subobject of Derived1 |
| 2739 | // } |
| 2740 | if (Qualifier && Qualifier->getAsType()) { |
| 2741 | QualType QType = QualType(Qualifier->getAsType(), 0); |
| 2742 | assert(QType->isRecordType() && "lookup done with non-record type" ); |
| 2743 | |
| 2744 | QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); |
| 2745 | |
| 2746 | // In C++98, the qualifier type doesn't actually have to be a base |
| 2747 | // type of the object type, in which case we just ignore it. |
| 2748 | // Otherwise build the appropriate casts. |
| 2749 | if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { |
| 2750 | CXXCastPath BasePath; |
| 2751 | if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, |
| 2752 | FromLoc, FromRange, &BasePath)) |
| 2753 | return ExprError(); |
| 2754 | |
| 2755 | if (PointerConversions) |
| 2756 | QType = Context.getPointerType(QType, |
| 2757 | FromType->isCHERICapabilityType(Context) |
| 2758 | ? ASTContext::PIK_Capability |
| 2759 | : ASTContext::PIK_Integer); |
| 2760 | From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, |
| 2761 | VK, &BasePath).get(); |
| 2762 | |
| 2763 | FromType = QType; |
| 2764 | FromRecordType = QRecordType; |
| 2765 | |
| 2766 | // If the qualifier type was the same as the destination type, |
| 2767 | // we're done. |
| 2768 | if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) |
| 2769 | return From; |
| 2770 | } |
| 2771 | } |
| 2772 | |
| 2773 | bool IgnoreAccess = false; |
| 2774 | |
| 2775 | // If we actually found the member through a using declaration, cast |
| 2776 | // down to the using declaration's type. |
| 2777 | // |
| 2778 | // Pointer equality is fine here because only one declaration of a |
| 2779 | // class ever has member declarations. |
| 2780 | if (FoundDecl->getDeclContext() != Member->getDeclContext()) { |
| 2781 | assert(isa<UsingShadowDecl>(FoundDecl)); |
| 2782 | QualType URecordType = Context.getTypeDeclType( |
| 2783 | cast<CXXRecordDecl>(FoundDecl->getDeclContext())); |
| 2784 | |
| 2785 | // We only need to do this if the naming-class to declaring-class |
| 2786 | // conversion is non-trivial. |
| 2787 | if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { |
| 2788 | assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); |
| 2789 | CXXCastPath BasePath; |
| 2790 | if (CheckDerivedToBaseConversion(FromRecordType, URecordType, |
| 2791 | FromLoc, FromRange, &BasePath)) |
| 2792 | return ExprError(); |
| 2793 | |
| 2794 | QualType UType = URecordType; |
| 2795 | if (PointerConversions) |
| 2796 | UType = Context.getPointerType(UType, |
| 2797 | FromType->isCHERICapabilityType(Context) |
| 2798 | ? ASTContext::PIK_Capability |
| 2799 | : ASTContext::PIK_Integer); |
| 2800 | From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, |
| 2801 | VK, &BasePath).get(); |
| 2802 | FromType = UType; |
| 2803 | FromRecordType = URecordType; |
| 2804 | } |
| 2805 | |
| 2806 | // We don't do access control for the conversion from the |
| 2807 | // declaring class to the true declaring class. |
| 2808 | IgnoreAccess = true; |
| 2809 | } |
| 2810 | |
| 2811 | CXXCastPath BasePath; |
| 2812 | if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, |
| 2813 | FromLoc, FromRange, &BasePath, |
| 2814 | IgnoreAccess)) |
| 2815 | return ExprError(); |
| 2816 | |
| 2817 | return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, |
| 2818 | VK, &BasePath); |
| 2819 | } |
| 2820 | |
| 2821 | bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, |
| 2822 | const LookupResult &R, |
| 2823 | bool HasTrailingLParen) { |
| 2824 | // Only when used directly as the postfix-expression of a call. |
| 2825 | if (!HasTrailingLParen) |
| 2826 | return false; |
| 2827 | |
| 2828 | // Never if a scope specifier was provided. |
| 2829 | if (SS.isSet()) |
| 2830 | return false; |
| 2831 | |
| 2832 | // Only in C++ or ObjC++. |
| 2833 | if (!getLangOpts().CPlusPlus) |
| 2834 | return false; |
| 2835 | |
| 2836 | // Turn off ADL when we find certain kinds of declarations during |
| 2837 | // normal lookup: |
| 2838 | for (NamedDecl *D : R) { |
| 2839 | // C++0x [basic.lookup.argdep]p3: |
| 2840 | // -- a declaration of a class member |
| 2841 | // Since using decls preserve this property, we check this on the |
| 2842 | // original decl. |
| 2843 | if (D->isCXXClassMember()) |
| 2844 | return false; |
| 2845 | |
| 2846 | // C++0x [basic.lookup.argdep]p3: |
| 2847 | // -- a block-scope function declaration that is not a |
| 2848 | // using-declaration |
| 2849 | // NOTE: we also trigger this for function templates (in fact, we |
| 2850 | // don't check the decl type at all, since all other decl types |
| 2851 | // turn off ADL anyway). |
| 2852 | if (isa<UsingShadowDecl>(D)) |
| 2853 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); |
| 2854 | else if (D->getLexicalDeclContext()->isFunctionOrMethod()) |
| 2855 | return false; |
| 2856 | |
| 2857 | // C++0x [basic.lookup.argdep]p3: |
| 2858 | // -- a declaration that is neither a function or a function |
| 2859 | // template |
| 2860 | // And also for builtin functions. |
| 2861 | if (isa<FunctionDecl>(D)) { |
| 2862 | FunctionDecl *FDecl = cast<FunctionDecl>(D); |
| 2863 | |
| 2864 | // But also builtin functions. |
| 2865 | if (FDecl->getBuiltinID() && FDecl->isImplicit()) |
| 2866 | return false; |
| 2867 | } else if (!isa<FunctionTemplateDecl>(D)) |
| 2868 | return false; |
| 2869 | } |
| 2870 | |
| 2871 | return true; |
| 2872 | } |
| 2873 | |
| 2874 | |
| 2875 | /// Diagnoses obvious problems with the use of the given declaration |
| 2876 | /// as an expression. This is only actually called for lookups that |
| 2877 | /// were not overloaded, and it doesn't promise that the declaration |
| 2878 | /// will in fact be used. |
| 2879 | static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { |
| 2880 | if (D->isInvalidDecl()) |
| 2881 | return true; |
| 2882 | |
| 2883 | if (isa<TypedefNameDecl>(D)) { |
| 2884 | S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); |
| 2885 | return true; |
| 2886 | } |
| 2887 | |
| 2888 | if (isa<ObjCInterfaceDecl>(D)) { |
| 2889 | S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); |
| 2890 | return true; |
| 2891 | } |
| 2892 | |
| 2893 | if (isa<NamespaceDecl>(D)) { |
| 2894 | S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); |
| 2895 | return true; |
| 2896 | } |
| 2897 | |
| 2898 | return false; |
| 2899 | } |
| 2900 | |
| 2901 | // Certain multiversion types should be treated as overloaded even when there is |
| 2902 | // only one result. |
| 2903 | static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { |
| 2904 | assert(R.isSingleResult() && "Expected only a single result" ); |
| 2905 | const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); |
| 2906 | return FD && |
| 2907 | (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); |
| 2908 | } |
| 2909 | |
| 2910 | ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, |
| 2911 | LookupResult &R, bool NeedsADL, |
| 2912 | bool AcceptInvalidDecl) { |
| 2913 | // If this is a single, fully-resolved result and we don't need ADL, |
| 2914 | // just build an ordinary singleton decl ref. |
| 2915 | if (!NeedsADL && R.isSingleResult() && |
| 2916 | !R.getAsSingle<FunctionTemplateDecl>() && |
| 2917 | !ShouldLookupResultBeMultiVersionOverload(R)) |
| 2918 | return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), |
| 2919 | R.getRepresentativeDecl(), nullptr, |
| 2920 | AcceptInvalidDecl); |
| 2921 | |
| 2922 | // We only need to check the declaration if there's exactly one |
| 2923 | // result, because in the overloaded case the results can only be |
| 2924 | // functions and function templates. |
| 2925 | if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && |
| 2926 | CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) |
| 2927 | return ExprError(); |
| 2928 | |
| 2929 | // Otherwise, just build an unresolved lookup expression. Suppress |
| 2930 | // any lookup-related diagnostics; we'll hash these out later, when |
| 2931 | // we've picked a target. |
| 2932 | R.suppressDiagnostics(); |
| 2933 | |
| 2934 | UnresolvedLookupExpr *ULE |
| 2935 | = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), |
| 2936 | SS.getWithLocInContext(Context), |
| 2937 | R.getLookupNameInfo(), |
| 2938 | NeedsADL, R.isOverloadedResult(), |
| 2939 | R.begin(), R.end()); |
| 2940 | |
| 2941 | return ULE; |
| 2942 | } |
| 2943 | |
| 2944 | static void |
| 2945 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, |
| 2946 | ValueDecl *var, DeclContext *DC); |
| 2947 | |
| 2948 | /// Complete semantic analysis for a reference to the given declaration. |
| 2949 | ExprResult Sema::BuildDeclarationNameExpr( |
| 2950 | const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, |
| 2951 | NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, |
| 2952 | bool AcceptInvalidDecl) { |
| 2953 | assert(D && "Cannot refer to a NULL declaration" ); |
| 2954 | assert(!isa<FunctionTemplateDecl>(D) && |
| 2955 | "Cannot refer unambiguously to a function template" ); |
| 2956 | |
| 2957 | SourceLocation Loc = NameInfo.getLoc(); |
| 2958 | if (CheckDeclInExpr(*this, Loc, D)) |
| 2959 | return ExprError(); |
| 2960 | |
| 2961 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { |
| 2962 | // Specifically diagnose references to class templates that are missing |
| 2963 | // a template argument list. |
| 2964 | diagnoseMissingTemplateArguments(TemplateName(Template), Loc); |
| 2965 | return ExprError(); |
| 2966 | } |
| 2967 | |
| 2968 | // Make sure that we're referring to a value. |
| 2969 | ValueDecl *VD = dyn_cast<ValueDecl>(D); |
| 2970 | if (!VD) { |
| 2971 | Diag(Loc, diag::err_ref_non_value) |
| 2972 | << D << SS.getRange(); |
| 2973 | Diag(D->getLocation(), diag::note_declared_at); |
| 2974 | return ExprError(); |
| 2975 | } |
| 2976 | |
| 2977 | // Check whether this declaration can be used. Note that we suppress |
| 2978 | // this check when we're going to perform argument-dependent lookup |
| 2979 | // on this function name, because this might not be the function |
| 2980 | // that overload resolution actually selects. |
| 2981 | if (DiagnoseUseOfDecl(VD, Loc)) |
| 2982 | return ExprError(); |
| 2983 | |
| 2984 | // Only create DeclRefExpr's for valid Decl's. |
| 2985 | if (VD->isInvalidDecl() && !AcceptInvalidDecl) |
| 2986 | return ExprError(); |
| 2987 | |
| 2988 | // Handle members of anonymous structs and unions. If we got here, |
| 2989 | // and the reference is to a class member indirect field, then this |
| 2990 | // must be the subject of a pointer-to-member expression. |
| 2991 | if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) |
| 2992 | if (!indirectField->isCXXClassMember()) |
| 2993 | return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), |
| 2994 | indirectField); |
| 2995 | |
| 2996 | { |
| 2997 | QualType type = VD->getType(); |
| 2998 | if (type.isNull()) |
| 2999 | return ExprError(); |
| 3000 | if (auto *FPT = type->getAs<FunctionProtoType>()) { |
| 3001 | // C++ [except.spec]p17: |
| 3002 | // An exception-specification is considered to be needed when: |
| 3003 | // - in an expression, the function is the unique lookup result or |
| 3004 | // the selected member of a set of overloaded functions. |
| 3005 | ResolveExceptionSpec(Loc, FPT); |
| 3006 | type = VD->getType(); |
| 3007 | } |
| 3008 | ExprValueKind valueKind = VK_RValue; |
| 3009 | |
| 3010 | switch (D->getKind()) { |
| 3011 | // Ignore all the non-ValueDecl kinds. |
| 3012 | #define ABSTRACT_DECL(kind) |
| 3013 | #define VALUE(type, base) |
| 3014 | #define DECL(type, base) \ |
| 3015 | case Decl::type: |
| 3016 | #include "clang/AST/DeclNodes.inc" |
| 3017 | llvm_unreachable("invalid value decl kind" ); |
| 3018 | |
| 3019 | // These shouldn't make it here. |
| 3020 | case Decl::ObjCAtDefsField: |
| 3021 | llvm_unreachable("forming non-member reference to ivar?" ); |
| 3022 | |
| 3023 | // Enum constants are always r-values and never references. |
| 3024 | // Unresolved using declarations are dependent. |
| 3025 | case Decl::EnumConstant: |
| 3026 | case Decl::UnresolvedUsingValue: |
| 3027 | case Decl::OMPDeclareReduction: |
| 3028 | case Decl::OMPDeclareMapper: |
| 3029 | valueKind = VK_RValue; |
| 3030 | break; |
| 3031 | |
| 3032 | // Fields and indirect fields that got here must be for |
| 3033 | // pointer-to-member expressions; we just call them l-values for |
| 3034 | // internal consistency, because this subexpression doesn't really |
| 3035 | // exist in the high-level semantics. |
| 3036 | case Decl::Field: |
| 3037 | case Decl::IndirectField: |
| 3038 | case Decl::ObjCIvar: |
| 3039 | assert(getLangOpts().CPlusPlus && |
| 3040 | "building reference to field in C?" ); |
| 3041 | |
| 3042 | // These can't have reference type in well-formed programs, but |
| 3043 | // for internal consistency we do this anyway. |
| 3044 | type = type.getNonReferenceType(); |
| 3045 | valueKind = VK_LValue; |
| 3046 | break; |
| 3047 | |
| 3048 | // Non-type template parameters are either l-values or r-values |
| 3049 | // depending on the type. |
| 3050 | case Decl::NonTypeTemplateParm: { |
| 3051 | if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { |
| 3052 | type = reftype->getPointeeType(); |
| 3053 | valueKind = VK_LValue; // even if the parameter is an r-value reference |
| 3054 | break; |
| 3055 | } |
| 3056 | |
| 3057 | // For non-references, we need to strip qualifiers just in case |
| 3058 | // the template parameter was declared as 'const int' or whatever. |
| 3059 | valueKind = VK_RValue; |
| 3060 | type = type.getUnqualifiedType(); |
| 3061 | break; |
| 3062 | } |
| 3063 | |
| 3064 | case Decl::Var: |
| 3065 | case Decl::VarTemplateSpecialization: |
| 3066 | case Decl::VarTemplatePartialSpecialization: |
| 3067 | case Decl::Decomposition: |
| 3068 | case Decl::OMPCapturedExpr: |
| 3069 | // In C, "extern void blah;" is valid and is an r-value. |
| 3070 | if (!getLangOpts().CPlusPlus && |
| 3071 | !type.hasQualifiers() && |
| 3072 | type->isVoidType()) { |
| 3073 | valueKind = VK_RValue; |
| 3074 | break; |
| 3075 | } |
| 3076 | LLVM_FALLTHROUGH; |
| 3077 | |
| 3078 | case Decl::ImplicitParam: |
| 3079 | case Decl::ParmVar: { |
| 3080 | // These are always l-values. |
| 3081 | valueKind = VK_LValue; |
| 3082 | type = type.getNonReferenceType(); |
| 3083 | |
| 3084 | // FIXME: Does the addition of const really only apply in |
| 3085 | // potentially-evaluated contexts? Since the variable isn't actually |
| 3086 | // captured in an unevaluated context, it seems that the answer is no. |
| 3087 | if (!isUnevaluatedContext()) { |
| 3088 | QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); |
| 3089 | if (!CapturedType.isNull()) |
| 3090 | type = CapturedType; |
| 3091 | } |
| 3092 | |
| 3093 | break; |
| 3094 | } |
| 3095 | |
| 3096 | case Decl::Binding: { |
| 3097 | // These are always lvalues. |
| 3098 | valueKind = VK_LValue; |
| 3099 | type = type.getNonReferenceType(); |
| 3100 | // FIXME: Support lambda-capture of BindingDecls, once CWG actually |
| 3101 | // decides how that's supposed to work. |
| 3102 | auto *BD = cast<BindingDecl>(VD); |
| 3103 | if (BD->getDeclContext() != CurContext) { |
| 3104 | auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); |
| 3105 | if (DD && DD->hasLocalStorage()) |
| 3106 | diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); |
| 3107 | } |
| 3108 | break; |
| 3109 | } |
| 3110 | |
| 3111 | case Decl::Function: { |
| 3112 | if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { |
| 3113 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { |
| 3114 | type = Context.BuiltinFnTy; |
| 3115 | valueKind = VK_RValue; |
| 3116 | break; |
| 3117 | } |
| 3118 | } |
| 3119 | |
| 3120 | const FunctionType *fty = type->castAs<FunctionType>(); |
| 3121 | |
| 3122 | // If we're referring to a function with an __unknown_anytype |
| 3123 | // result type, make the entire expression __unknown_anytype. |
| 3124 | if (fty->getReturnType() == Context.UnknownAnyTy) { |
| 3125 | type = Context.UnknownAnyTy; |
| 3126 | valueKind = VK_RValue; |
| 3127 | break; |
| 3128 | } |
| 3129 | |
| 3130 | // Functions are l-values in C++. |
| 3131 | if (getLangOpts().CPlusPlus) { |
| 3132 | valueKind = VK_LValue; |
| 3133 | break; |
| 3134 | } |
| 3135 | |
| 3136 | // C99 DR 316 says that, if a function type comes from a |
| 3137 | // function definition (without a prototype), that type is only |
| 3138 | // used for checking compatibility. Therefore, when referencing |
| 3139 | // the function, we pretend that we don't have the full function |
| 3140 | // type. |
| 3141 | if (!cast<FunctionDecl>(VD)->hasPrototype() && |
| 3142 | isa<FunctionProtoType>(fty)) |
| 3143 | type = Context.getFunctionNoProtoType(fty->getReturnType(), |
| 3144 | fty->getExtInfo()); |
| 3145 | |
| 3146 | // Functions are r-values in C. |
| 3147 | valueKind = VK_RValue; |
| 3148 | break; |
| 3149 | } |
| 3150 | |
| 3151 | case Decl::CXXDeductionGuide: |
| 3152 | llvm_unreachable("building reference to deduction guide" ); |
| 3153 | |
| 3154 | case Decl::MSProperty: |
| 3155 | valueKind = VK_LValue; |
| 3156 | break; |
| 3157 | |
| 3158 | case Decl::CXXMethod: |
| 3159 | // If we're referring to a method with an __unknown_anytype |
| 3160 | // result type, make the entire expression __unknown_anytype. |
| 3161 | // This should only be possible with a type written directly. |
| 3162 | if (const FunctionProtoType *proto |
| 3163 | = dyn_cast<FunctionProtoType>(VD->getType())) |
| 3164 | if (proto->getReturnType() == Context.UnknownAnyTy) { |
| 3165 | type = Context.UnknownAnyTy; |
| 3166 | valueKind = VK_RValue; |
| 3167 | break; |
| 3168 | } |
| 3169 | |
| 3170 | // C++ methods are l-values if static, r-values if non-static. |
| 3171 | if (cast<CXXMethodDecl>(VD)->isStatic()) { |
| 3172 | valueKind = VK_LValue; |
| 3173 | break; |
| 3174 | } |
| 3175 | LLVM_FALLTHROUGH; |
| 3176 | |
| 3177 | case Decl::CXXConversion: |
| 3178 | case Decl::CXXDestructor: |
| 3179 | case Decl::CXXConstructor: |
| 3180 | valueKind = VK_RValue; |
| 3181 | break; |
| 3182 | } |
| 3183 | |
| 3184 | return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, |
| 3185 | /*FIXME: TemplateKWLoc*/ SourceLocation(), |
| 3186 | TemplateArgs); |
| 3187 | } |
| 3188 | } |
| 3189 | |
| 3190 | static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, |
| 3191 | SmallString<32> &Target) { |
| 3192 | Target.resize(CharByteWidth * (Source.size() + 1)); |
| 3193 | char *ResultPtr = &Target[0]; |
| 3194 | const llvm::UTF8 *ErrorPtr; |
| 3195 | bool success = |
| 3196 | llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); |
| 3197 | (void)success; |
| 3198 | assert(success); |
| 3199 | Target.resize(ResultPtr - &Target[0]); |
| 3200 | } |
| 3201 | |
| 3202 | ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, |
| 3203 | PredefinedExpr::IdentKind IK) { |
| 3204 | // Pick the current block, lambda, captured statement or function. |
| 3205 | Decl *currentDecl = nullptr; |
| 3206 | if (const BlockScopeInfo *BSI = getCurBlock()) |
| 3207 | currentDecl = BSI->TheDecl; |
| 3208 | else if (const LambdaScopeInfo *LSI = getCurLambda()) |
| 3209 | currentDecl = LSI->CallOperator; |
| 3210 | else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) |
| 3211 | currentDecl = CSI->TheCapturedDecl; |
| 3212 | else |
| 3213 | currentDecl = getCurFunctionOrMethodDecl(); |
| 3214 | |
| 3215 | if (!currentDecl) { |
| 3216 | Diag(Loc, diag::ext_predef_outside_function); |
| 3217 | currentDecl = Context.getTranslationUnitDecl(); |
| 3218 | } |
| 3219 | |
| 3220 | QualType ResTy; |
| 3221 | StringLiteral *SL = nullptr; |
| 3222 | if (cast<DeclContext>(currentDecl)->isDependentContext()) |
| 3223 | ResTy = Context.DependentTy; |
| 3224 | else { |
| 3225 | // Pre-defined identifiers are of type char[x], where x is the length of |
| 3226 | // the string. |
| 3227 | auto Str = PredefinedExpr::ComputeName(IK, currentDecl); |
| 3228 | unsigned Length = Str.length(); |
| 3229 | |
| 3230 | llvm::APInt LengthI(32, Length + 1); |
| 3231 | if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { |
| 3232 | ResTy = |
| 3233 | Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); |
| 3234 | SmallString<32> RawChars; |
| 3235 | ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), |
| 3236 | Str, RawChars); |
| 3237 | ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, |
| 3238 | /*IndexTypeQuals*/ 0); |
| 3239 | SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, |
| 3240 | /*Pascal*/ false, ResTy, Loc); |
| 3241 | } else { |
| 3242 | ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); |
| 3243 | ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, |
| 3244 | /*IndexTypeQuals*/ 0); |
| 3245 | SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, |
| 3246 | /*Pascal*/ false, ResTy, Loc); |
| 3247 | } |
| 3248 | } |
| 3249 | |
| 3250 | return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); |
| 3251 | } |
| 3252 | |
| 3253 | ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { |
| 3254 | PredefinedExpr::IdentKind IK; |
| 3255 | |
| 3256 | switch (Kind) { |
| 3257 | default: llvm_unreachable("Unknown simple primary expr!" ); |
| 3258 | case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] |
| 3259 | case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; |
| 3260 | case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] |
| 3261 | case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] |
| 3262 | case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] |
| 3263 | case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] |
| 3264 | case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; |
| 3265 | } |
| 3266 | |
| 3267 | return BuildPredefinedExpr(Loc, IK); |
| 3268 | } |
| 3269 | |
| 3270 | ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { |
| 3271 | SmallString<16> CharBuffer; |
| 3272 | bool Invalid = false; |
| 3273 | StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); |
| 3274 | if (Invalid) |
| 3275 | return ExprError(); |
| 3276 | |
| 3277 | CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), |
| 3278 | PP, Tok.getKind()); |
| 3279 | if (Literal.hadError()) |
| 3280 | return ExprError(); |
| 3281 | |
| 3282 | QualType Ty; |
| 3283 | if (Literal.isWide()) |
| 3284 | Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. |
| 3285 | else if (Literal.isUTF8() && getLangOpts().Char8) |
| 3286 | Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. |
| 3287 | else if (Literal.isUTF16()) |
| 3288 | Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. |
| 3289 | else if (Literal.isUTF32()) |
| 3290 | Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. |
| 3291 | else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) |
| 3292 | Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. |
| 3293 | else |
| 3294 | Ty = Context.CharTy; // 'x' -> char in C++ |
| 3295 | |
| 3296 | CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; |
| 3297 | if (Literal.isWide()) |
| 3298 | Kind = CharacterLiteral::Wide; |
| 3299 | else if (Literal.isUTF16()) |
| 3300 | Kind = CharacterLiteral::UTF16; |
| 3301 | else if (Literal.isUTF32()) |
| 3302 | Kind = CharacterLiteral::UTF32; |
| 3303 | else if (Literal.isUTF8()) |
| 3304 | Kind = CharacterLiteral::UTF8; |
| 3305 | |
| 3306 | Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, |
| 3307 | Tok.getLocation()); |
| 3308 | |
| 3309 | if (Literal.getUDSuffix().empty()) |
| 3310 | return Lit; |
| 3311 | |
| 3312 | // We're building a user-defined literal. |
| 3313 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); |
| 3314 | SourceLocation UDSuffixLoc = |
| 3315 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); |
| 3316 | |
| 3317 | // Make sure we're allowed user-defined literals here. |
| 3318 | if (!UDLScope) |
| 3319 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); |
| 3320 | |
| 3321 | // C++11 [lex.ext]p6: The literal L is treated as a call of the form |
| 3322 | // operator "" X (ch) |
| 3323 | return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, |
| 3324 | Lit, Tok.getLocation()); |
| 3325 | } |
| 3326 | |
| 3327 | ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { |
| 3328 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
| 3329 | return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), |
| 3330 | Context.IntTy, Loc); |
| 3331 | } |
| 3332 | |
| 3333 | static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, |
| 3334 | QualType Ty, SourceLocation Loc) { |
| 3335 | const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); |
| 3336 | |
| 3337 | using llvm::APFloat; |
| 3338 | APFloat Val(Format); |
| 3339 | |
| 3340 | APFloat::opStatus result = Literal.GetFloatValue(Val); |
| 3341 | |
| 3342 | // Overflow is always an error, but underflow is only an error if |
| 3343 | // we underflowed to zero (APFloat reports denormals as underflow). |
| 3344 | if ((result & APFloat::opOverflow) || |
| 3345 | ((result & APFloat::opUnderflow) && Val.isZero())) { |
| 3346 | unsigned diagnostic; |
| 3347 | SmallString<20> buffer; |
| 3348 | if (result & APFloat::opOverflow) { |
| 3349 | diagnostic = diag::warn_float_overflow; |
| 3350 | APFloat::getLargest(Format).toString(buffer); |
| 3351 | } else { |
| 3352 | diagnostic = diag::warn_float_underflow; |
| 3353 | APFloat::getSmallest(Format).toString(buffer); |
| 3354 | } |
| 3355 | |
| 3356 | S.Diag(Loc, diagnostic) |
| 3357 | << Ty |
| 3358 | << StringRef(buffer.data(), buffer.size()); |
| 3359 | } |
| 3360 | |
| 3361 | bool isExact = (result == APFloat::opOK); |
| 3362 | return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); |
| 3363 | } |
| 3364 | |
| 3365 | bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { |
| 3366 | assert(E && "Invalid expression" ); |
| 3367 | |
| 3368 | if (E->isValueDependent()) |
| 3369 | return false; |
| 3370 | |
| 3371 | QualType QT = E->getType(); |
| 3372 | if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { |
| 3373 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; |
| 3374 | return true; |
| 3375 | } |
| 3376 | |
| 3377 | llvm::APSInt ValueAPS; |
| 3378 | ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); |
| 3379 | |
| 3380 | if (R.isInvalid()) |
| 3381 | return true; |
| 3382 | |
| 3383 | bool ValueIsPositive = ValueAPS.isStrictlyPositive(); |
| 3384 | if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { |
| 3385 | Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) |
| 3386 | << ValueAPS.toString(10) << ValueIsPositive; |
| 3387 | return true; |
| 3388 | } |
| 3389 | |
| 3390 | return false; |
| 3391 | } |
| 3392 | |
| 3393 | ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { |
| 3394 | // Fast path for a single digit (which is quite common). A single digit |
| 3395 | // cannot have a trigraph, escaped newline, radix prefix, or suffix. |
| 3396 | if (Tok.getLength() == 1) { |
| 3397 | const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); |
| 3398 | return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); |
| 3399 | } |
| 3400 | |
| 3401 | SmallString<128> SpellingBuffer; |
| 3402 | // NumericLiteralParser wants to overread by one character. Add padding to |
| 3403 | // the buffer in case the token is copied to the buffer. If getSpelling() |
| 3404 | // returns a StringRef to the memory buffer, it should have a null char at |
| 3405 | // the EOF, so it is also safe. |
| 3406 | SpellingBuffer.resize(Tok.getLength() + 1); |
| 3407 | |
| 3408 | // Get the spelling of the token, which eliminates trigraphs, etc. |
| 3409 | bool Invalid = false; |
| 3410 | StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); |
| 3411 | if (Invalid) |
| 3412 | return ExprError(); |
| 3413 | |
| 3414 | NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); |
| 3415 | if (Literal.hadError) |
| 3416 | return ExprError(); |
| 3417 | |
| 3418 | if (Literal.hasUDSuffix()) { |
| 3419 | // We're building a user-defined literal. |
| 3420 | IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); |
| 3421 | SourceLocation UDSuffixLoc = |
| 3422 | getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); |
| 3423 | |
| 3424 | // Make sure we're allowed user-defined literals here. |
| 3425 | if (!UDLScope) |
| 3426 | return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); |
| 3427 | |
| 3428 | QualType CookedTy; |
| 3429 | if (Literal.isFloatingLiteral()) { |
| 3430 | // C++11 [lex.ext]p4: If S contains a literal operator with parameter type |
| 3431 | // long double, the literal is treated as a call of the form |
| 3432 | // operator "" X (f L) |
| 3433 | CookedTy = Context.LongDoubleTy; |
| 3434 | } else { |
| 3435 | // C++11 [lex.ext]p3: If S contains a literal operator with parameter type |
| 3436 | // unsigned long long, the literal is treated as a call of the form |
| 3437 | // operator "" X (n ULL) |
| 3438 | CookedTy = Context.UnsignedLongLongTy; |
| 3439 | } |
| 3440 | |
| 3441 | DeclarationName OpName = |
| 3442 | Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); |
| 3443 | DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); |
| 3444 | OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); |
| 3445 | |
| 3446 | SourceLocation TokLoc = Tok.getLocation(); |
| 3447 | |
| 3448 | // Perform literal operator lookup to determine if we're building a raw |
| 3449 | // literal or a cooked one. |
| 3450 | LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); |
| 3451 | switch (LookupLiteralOperator(UDLScope, R, CookedTy, |
| 3452 | /*AllowRaw*/ true, /*AllowTemplate*/ true, |
| 3453 | /*AllowStringTemplate*/ false, |
| 3454 | /*DiagnoseMissing*/ !Literal.isImaginary)) { |
| 3455 | case LOLR_ErrorNoDiagnostic: |
| 3456 | // Lookup failure for imaginary constants isn't fatal, there's still the |
| 3457 | // GNU extension producing _Complex types. |
| 3458 | break; |
| 3459 | case LOLR_Error: |
| 3460 | return ExprError(); |
| 3461 | case LOLR_Cooked: { |
| 3462 | Expr *Lit; |
| 3463 | if (Literal.isFloatingLiteral()) { |
| 3464 | Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); |
| 3465 | } else { |
| 3466 | llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); |
| 3467 | if (Literal.GetIntegerValue(ResultVal)) |
| 3468 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) |
| 3469 | << /* Unsigned */ 1; |
| 3470 | Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, |
| 3471 | Tok.getLocation()); |
| 3472 | } |
| 3473 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); |
| 3474 | } |
| 3475 | |
| 3476 | case LOLR_Raw: { |
| 3477 | // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the |
| 3478 | // literal is treated as a call of the form |
| 3479 | // operator "" X ("n") |
| 3480 | unsigned Length = Literal.getUDSuffixOffset(); |
| 3481 | QualType StrTy = Context.getConstantArrayType( |
| 3482 | Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), |
| 3483 | llvm::APInt(32, Length + 1), ArrayType::Normal, 0); |
| 3484 | Expr *Lit = StringLiteral::Create( |
| 3485 | Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, |
| 3486 | /*Pascal*/false, StrTy, &TokLoc, 1); |
| 3487 | return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); |
| 3488 | } |
| 3489 | |
| 3490 | case LOLR_Template: { |
| 3491 | // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator |
| 3492 | // template), L is treated as a call fo the form |
| 3493 | // operator "" X <'c1', 'c2', ... 'ck'>() |
| 3494 | // where n is the source character sequence c1 c2 ... ck. |
| 3495 | TemplateArgumentListInfo ExplicitArgs; |
| 3496 | unsigned CharBits = Context.getIntWidth(Context.CharTy); |
| 3497 | bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); |
| 3498 | llvm::APSInt Value(CharBits, CharIsUnsigned); |
| 3499 | for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { |
| 3500 | Value = TokSpelling[I]; |
| 3501 | TemplateArgument Arg(Context, Value, Context.CharTy); |
| 3502 | TemplateArgumentLocInfo ArgInfo; |
| 3503 | ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); |
| 3504 | } |
| 3505 | return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, |
| 3506 | &ExplicitArgs); |
| 3507 | } |
| 3508 | case LOLR_StringTemplate: |
| 3509 | llvm_unreachable("unexpected literal operator lookup result" ); |
| 3510 | } |
| 3511 | } |
| 3512 | |
| 3513 | Expr *Res; |
| 3514 | |
| 3515 | if (Literal.isFixedPointLiteral()) { |
| 3516 | QualType Ty; |
| 3517 | |
| 3518 | if (Literal.isAccum) { |
| 3519 | if (Literal.isHalf) { |
| 3520 | Ty = Context.ShortAccumTy; |
| 3521 | } else if (Literal.isLong) { |
| 3522 | Ty = Context.LongAccumTy; |
| 3523 | } else { |
| 3524 | Ty = Context.AccumTy; |
| 3525 | } |
| 3526 | } else if (Literal.isFract) { |
| 3527 | if (Literal.isHalf) { |
| 3528 | Ty = Context.ShortFractTy; |
| 3529 | } else if (Literal.isLong) { |
| 3530 | Ty = Context.LongFractTy; |
| 3531 | } else { |
| 3532 | Ty = Context.FractTy; |
| 3533 | } |
| 3534 | } |
| 3535 | |
| 3536 | if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); |
| 3537 | |
| 3538 | bool isSigned = !Literal.isUnsigned; |
| 3539 | unsigned scale = Context.getFixedPointScale(Ty); |
| 3540 | unsigned bit_width = Context.getTypeInfo(Ty).Width; |
| 3541 | |
| 3542 | llvm::APInt Val(bit_width, 0, isSigned); |
| 3543 | bool Overflowed = Literal.GetFixedPointValue(Val, scale); |
| 3544 | bool ValIsZero = Val.isNullValue() && !Overflowed; |
| 3545 | |
| 3546 | auto MaxVal = Context.getFixedPointMax(Ty).getValue(); |
| 3547 | if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) |
| 3548 | // Clause 6.4.4 - The value of a constant shall be in the range of |
| 3549 | // representable values for its type, with exception for constants of a |
| 3550 | // fract type with a value of exactly 1; such a constant shall denote |
| 3551 | // the maximal value for the type. |
| 3552 | --Val; |
| 3553 | else if (Val.ugt(MaxVal) || Overflowed) |
| 3554 | Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); |
| 3555 | |
| 3556 | Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, |
| 3557 | Tok.getLocation(), scale); |
| 3558 | } else if (Literal.isFloatingLiteral()) { |
| 3559 | QualType Ty; |
| 3560 | if (Literal.isHalf){ |
| 3561 | if (getOpenCLOptions().isEnabled("cl_khr_fp16" )) |
| 3562 | Ty = Context.HalfTy; |
| 3563 | else { |
| 3564 | Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); |
| 3565 | return ExprError(); |
| 3566 | } |
| 3567 | } else if (Literal.isFloat) |
| 3568 | Ty = Context.FloatTy; |
| 3569 | else if (Literal.isLong) |
| 3570 | Ty = Context.LongDoubleTy; |
| 3571 | else if (Literal.isFloat16) |
| 3572 | Ty = Context.Float16Ty; |
| 3573 | else if (Literal.isFloat128) |
| 3574 | Ty = Context.Float128Ty; |
| 3575 | else |
| 3576 | Ty = Context.DoubleTy; |
| 3577 | |
| 3578 | Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); |
| 3579 | |
| 3580 | if (Ty == Context.DoubleTy) { |
| 3581 | if (getLangOpts().SinglePrecisionConstants) { |
| 3582 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
| 3583 | if (BTy->getKind() != BuiltinType::Float) { |
| 3584 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); |
| 3585 | } |
| 3586 | } else if (getLangOpts().OpenCL && |
| 3587 | !getOpenCLOptions().isEnabled("cl_khr_fp64" )) { |
| 3588 | // Impose single-precision float type when cl_khr_fp64 is not enabled. |
| 3589 | Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); |
| 3590 | Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); |
| 3591 | } |
| 3592 | } |
| 3593 | } else if (!Literal.isIntegerLiteral()) { |
| 3594 | return ExprError(); |
| 3595 | } else { |
| 3596 | QualType Ty; |
| 3597 | |
| 3598 | // 'long long' is a C99 or C++11 feature. |
| 3599 | if (!getLangOpts().C99 && Literal.isLongLong) { |
| 3600 | if (getLangOpts().CPlusPlus) |
| 3601 | Diag(Tok.getLocation(), |
| 3602 | getLangOpts().CPlusPlus11 ? |
| 3603 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); |
| 3604 | else |
| 3605 | Diag(Tok.getLocation(), diag::ext_c99_longlong); |
| 3606 | } |
| 3607 | |
| 3608 | // Get the value in the widest-possible width. |
| 3609 | unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); |
| 3610 | llvm::APInt ResultVal(MaxWidth, 0); |
| 3611 | |
| 3612 | if (Literal.GetIntegerValue(ResultVal)) { |
| 3613 | // If this value didn't fit into uintmax_t, error and force to ull. |
| 3614 | Diag(Tok.getLocation(), diag::err_integer_literal_too_large) |
| 3615 | << /* Unsigned */ 1; |
| 3616 | Ty = Context.UnsignedLongLongTy; |
| 3617 | assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && |
| 3618 | "long long is not intmax_t?" ); |
| 3619 | } else { |
| 3620 | // If this value fits into a ULL, try to figure out what else it fits into |
| 3621 | // according to the rules of C99 6.4.4.1p5. |
| 3622 | |
| 3623 | // Octal, Hexadecimal, and integers with a U suffix are allowed to |
| 3624 | // be an unsigned int. |
| 3625 | bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; |
| 3626 | |
| 3627 | // Check from smallest to largest, picking the smallest type we can. |
| 3628 | unsigned Width = 0; |
| 3629 | |
| 3630 | // Microsoft specific integer suffixes are explicitly sized. |
| 3631 | if (Literal.MicrosoftInteger) { |
| 3632 | if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { |
| 3633 | Width = 8; |
| 3634 | Ty = Context.CharTy; |
| 3635 | } else { |
| 3636 | Width = Literal.MicrosoftInteger; |
| 3637 | Ty = Context.getIntTypeForBitwidth(Width, |
| 3638 | /*Signed=*/!Literal.isUnsigned); |
| 3639 | } |
| 3640 | } |
| 3641 | |
| 3642 | if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { |
| 3643 | // Are int/unsigned possibilities? |
| 3644 | unsigned IntSize = Context.getTargetInfo().getIntWidth(); |
| 3645 | |
| 3646 | // Does it fit in a unsigned int? |
| 3647 | if (ResultVal.isIntN(IntSize)) { |
| 3648 | // Does it fit in a signed int? |
| 3649 | if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) |
| 3650 | Ty = Context.IntTy; |
| 3651 | else if (AllowUnsigned) |
| 3652 | Ty = Context.UnsignedIntTy; |
| 3653 | Width = IntSize; |
| 3654 | } |
| 3655 | } |
| 3656 | |
| 3657 | // Are long/unsigned long possibilities? |
| 3658 | if (Ty.isNull() && !Literal.isLongLong) { |
| 3659 | unsigned LongSize = Context.getTargetInfo().getLongWidth(); |
| 3660 | |
| 3661 | // Does it fit in a unsigned long? |
| 3662 | if (ResultVal.isIntN(LongSize)) { |
| 3663 | // Does it fit in a signed long? |
| 3664 | if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) |
| 3665 | Ty = Context.LongTy; |
| 3666 | else if (AllowUnsigned) |
| 3667 | Ty = Context.UnsignedLongTy; |
| 3668 | // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 |
| 3669 | // is compatible. |
| 3670 | else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { |
| 3671 | const unsigned LongLongSize = |
| 3672 | Context.getTargetInfo().getLongLongWidth(); |
| 3673 | Diag(Tok.getLocation(), |
| 3674 | getLangOpts().CPlusPlus |
| 3675 | ? Literal.isLong |
| 3676 | ? diag::warn_old_implicitly_unsigned_long_cxx |
| 3677 | : /*C++98 UB*/ diag:: |
| 3678 | ext_old_implicitly_unsigned_long_cxx |
| 3679 | : diag::warn_old_implicitly_unsigned_long) |
| 3680 | << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 |
| 3681 | : /*will be ill-formed*/ 1); |
| 3682 | Ty = Context.UnsignedLongTy; |
| 3683 | } |
| 3684 | Width = LongSize; |
| 3685 | } |
| 3686 | } |
| 3687 | |
| 3688 | // Check long long if needed. |
| 3689 | if (Ty.isNull()) { |
| 3690 | unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); |
| 3691 | |
| 3692 | // Does it fit in a unsigned long long? |
| 3693 | if (ResultVal.isIntN(LongLongSize)) { |
| 3694 | // Does it fit in a signed long long? |
| 3695 | // To be compatible with MSVC, hex integer literals ending with the |
| 3696 | // LL or i64 suffix are always signed in Microsoft mode. |
| 3697 | if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || |
| 3698 | (getLangOpts().MSVCCompat && Literal.isLongLong))) |
| 3699 | Ty = Context.LongLongTy; |
| 3700 | else if (AllowUnsigned) |
| 3701 | Ty = Context.UnsignedLongLongTy; |
| 3702 | Width = LongLongSize; |
| 3703 | } |
| 3704 | } |
| 3705 | |
| 3706 | // If we still couldn't decide a type, we probably have something that |
| 3707 | // does not fit in a signed long long, but has no U suffix. |
| 3708 | if (Ty.isNull()) { |
| 3709 | Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); |
| 3710 | Ty = Context.UnsignedLongLongTy; |
| 3711 | Width = Context.getTargetInfo().getLongLongWidth(); |
| 3712 | } |
| 3713 | |
| 3714 | if (ResultVal.getBitWidth() != Width) |
| 3715 | ResultVal = ResultVal.trunc(Width); |
| 3716 | } |
| 3717 | Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); |
| 3718 | } |
| 3719 | |
| 3720 | // If this is an imaginary literal, create the ImaginaryLiteral wrapper. |
| 3721 | if (Literal.isImaginary) { |
| 3722 | Res = new (Context) ImaginaryLiteral(Res, |
| 3723 | Context.getComplexType(Res->getType())); |
| 3724 | |
| 3725 | Diag(Tok.getLocation(), diag::ext_imaginary_constant); |
| 3726 | } |
| 3727 | return Res; |
| 3728 | } |
| 3729 | |
| 3730 | ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { |
| 3731 | assert(E && "ActOnParenExpr() missing expr" ); |
| 3732 | return new (Context) ParenExpr(L, R, E); |
| 3733 | } |
| 3734 | |
| 3735 | static bool CheckVecStepTraitOperandType(Sema &S, QualType T, |
| 3736 | SourceLocation Loc, |
| 3737 | SourceRange ArgRange) { |
| 3738 | // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in |
| 3739 | // scalar or vector data type argument..." |
| 3740 | // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic |
| 3741 | // type (C99 6.2.5p18) or void. |
| 3742 | if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { |
| 3743 | S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) |
| 3744 | << T << ArgRange; |
| 3745 | return true; |
| 3746 | } |
| 3747 | |
| 3748 | assert((T->isVoidType() || !T->isIncompleteType()) && |
| 3749 | "Scalar types should always be complete" ); |
| 3750 | return false; |
| 3751 | } |
| 3752 | |
| 3753 | static bool CheckExtensionTraitOperandType(Sema &S, QualType T, |
| 3754 | SourceLocation Loc, |
| 3755 | SourceRange ArgRange, |
| 3756 | UnaryExprOrTypeTrait TraitKind) { |
| 3757 | // Invalid types must be hard errors for SFINAE in C++. |
| 3758 | if (S.LangOpts.CPlusPlus) |
| 3759 | return true; |
| 3760 | |
| 3761 | // C99 6.5.3.4p1: |
| 3762 | if (T->isFunctionType() && |
| 3763 | (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || |
| 3764 | TraitKind == UETT_PreferredAlignOf)) { |
| 3765 | // sizeof(function)/alignof(function) is allowed as an extension. |
| 3766 | S.Diag(Loc, diag::ext_sizeof_alignof_function_type) |
| 3767 | << TraitKind << ArgRange; |
| 3768 | return false; |
| 3769 | } |
| 3770 | |
| 3771 | // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where |
| 3772 | // this is an error (OpenCL v1.1 s6.3.k) |
| 3773 | if (T->isVoidType()) { |
| 3774 | unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type |
| 3775 | : diag::ext_sizeof_alignof_void_type; |
| 3776 | S.Diag(Loc, DiagID) << TraitKind << ArgRange; |
| 3777 | return false; |
| 3778 | } |
| 3779 | |
| 3780 | return true; |
| 3781 | } |
| 3782 | |
| 3783 | static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, |
| 3784 | SourceLocation Loc, |
| 3785 | SourceRange ArgRange, |
| 3786 | UnaryExprOrTypeTrait TraitKind) { |
| 3787 | // Reject sizeof(interface) and sizeof(interface<proto>) if the |
| 3788 | // runtime doesn't allow it. |
| 3789 | if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { |
| 3790 | S.Diag(Loc, diag::err_sizeof_nonfragile_interface) |
| 3791 | << T << (TraitKind == UETT_SizeOf) |
| 3792 | << ArgRange; |
| 3793 | return true; |
| 3794 | } |
| 3795 | |
| 3796 | return false; |
| 3797 | } |
| 3798 | |
| 3799 | /// Check whether E is a pointer from a decayed array type (the decayed |
| 3800 | /// pointer type is equal to T) and emit a warning if it is. |
| 3801 | static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, |
| 3802 | Expr *E) { |
| 3803 | // Don't warn if the operation changed the type. |
| 3804 | if (T != E->getType()) |
| 3805 | return; |
| 3806 | |
| 3807 | // Now look for array decays. |
| 3808 | ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); |
| 3809 | if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) |
| 3810 | return; |
| 3811 | |
| 3812 | S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() |
| 3813 | << ICE->getType() |
| 3814 | << ICE->getSubExpr()->getType(); |
| 3815 | } |
| 3816 | |
| 3817 | /// Check the constraints on expression operands to unary type expression |
| 3818 | /// and type traits. |
| 3819 | /// |
| 3820 | /// Completes any types necessary and validates the constraints on the operand |
| 3821 | /// expression. The logic mostly mirrors the type-based overload, but may modify |
| 3822 | /// the expression as it completes the type for that expression through template |
| 3823 | /// instantiation, etc. |
| 3824 | bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, |
| 3825 | UnaryExprOrTypeTrait ExprKind) { |
| 3826 | QualType ExprTy = E->getType(); |
| 3827 | assert(!ExprTy->isReferenceType()); |
| 3828 | |
| 3829 | if (ExprKind == UETT_VecStep) |
| 3830 | return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), |
| 3831 | E->getSourceRange()); |
| 3832 | |
| 3833 | // Whitelist some types as extensions |
| 3834 | if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), |
| 3835 | E->getSourceRange(), ExprKind)) |
| 3836 | return false; |
| 3837 | |
| 3838 | // 'alignof' applied to an expression only requires the base element type of |
| 3839 | // the expression to be complete. 'sizeof' requires the expression's type to |
| 3840 | // be complete (and will attempt to complete it if it's an array of unknown |
| 3841 | // bound). |
| 3842 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
| 3843 | if (RequireCompleteType(E->getExprLoc(), |
| 3844 | Context.getBaseElementType(E->getType()), |
| 3845 | diag::err_sizeof_alignof_incomplete_type, ExprKind, |
| 3846 | E->getSourceRange())) |
| 3847 | return true; |
| 3848 | } else { |
| 3849 | if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, |
| 3850 | ExprKind, E->getSourceRange())) |
| 3851 | return true; |
| 3852 | } |
| 3853 | |
| 3854 | // Completing the expression's type may have changed it. |
| 3855 | ExprTy = E->getType(); |
| 3856 | assert(!ExprTy->isReferenceType()); |
| 3857 | |
| 3858 | if (ExprTy->isFunctionType()) { |
| 3859 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) |
| 3860 | << ExprKind << E->getSourceRange(); |
| 3861 | return true; |
| 3862 | } |
| 3863 | |
| 3864 | // The operand for sizeof and alignof is in an unevaluated expression context, |
| 3865 | // so side effects could result in unintended consequences. |
| 3866 | if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || |
| 3867 | ExprKind == UETT_PreferredAlignOf) && |
| 3868 | !inTemplateInstantiation() && E->HasSideEffects(Context, false)) |
| 3869 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
| 3870 | |
| 3871 | if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), |
| 3872 | E->getSourceRange(), ExprKind)) |
| 3873 | return true; |
| 3874 | |
| 3875 | if (ExprKind == UETT_SizeOf) { |
| 3876 | if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { |
| 3877 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { |
| 3878 | QualType OType = PVD->getOriginalType(); |
| 3879 | QualType Type = PVD->getType(); |
| 3880 | if (Type->isPointerType() && OType->isArrayType()) { |
| 3881 | Diag(E->getExprLoc(), diag::warn_sizeof_array_param) |
| 3882 | << Type << OType; |
| 3883 | Diag(PVD->getLocation(), diag::note_declared_at); |
| 3884 | } |
| 3885 | } |
| 3886 | } |
| 3887 | |
| 3888 | // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array |
| 3889 | // decays into a pointer and returns an unintended result. This is most |
| 3890 | // likely a typo for "sizeof(array) op x". |
| 3891 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { |
| 3892 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), |
| 3893 | BO->getLHS()); |
| 3894 | warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), |
| 3895 | BO->getRHS()); |
| 3896 | } |
| 3897 | } |
| 3898 | |
| 3899 | return false; |
| 3900 | } |
| 3901 | |
| 3902 | /// Check the constraints on operands to unary expression and type |
| 3903 | /// traits. |
| 3904 | /// |
| 3905 | /// This will complete any types necessary, and validate the various constraints |
| 3906 | /// on those operands. |
| 3907 | /// |
| 3908 | /// The UsualUnaryConversions() function is *not* called by this routine. |
| 3909 | /// C99 6.3.2.1p[2-4] all state: |
| 3910 | /// Except when it is the operand of the sizeof operator ... |
| 3911 | /// |
| 3912 | /// C++ [expr.sizeof]p4 |
| 3913 | /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer |
| 3914 | /// standard conversions are not applied to the operand of sizeof. |
| 3915 | /// |
| 3916 | /// This policy is followed for all of the unary trait expressions. |
| 3917 | bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, |
| 3918 | SourceLocation OpLoc, |
| 3919 | SourceRange ExprRange, |
| 3920 | UnaryExprOrTypeTrait ExprKind) { |
| 3921 | if (ExprType->isDependentType()) |
| 3922 | return false; |
| 3923 | |
| 3924 | // C++ [expr.sizeof]p2: |
| 3925 | // When applied to a reference or a reference type, the result |
| 3926 | // is the size of the referenced type. |
| 3927 | // C++11 [expr.alignof]p3: |
| 3928 | // When alignof is applied to a reference type, the result |
| 3929 | // shall be the alignment of the referenced type. |
| 3930 | if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) |
| 3931 | ExprType = Ref->getPointeeType(); |
| 3932 | |
| 3933 | // C11 6.5.3.4/3, C++11 [expr.alignof]p3: |
| 3934 | // When alignof or _Alignof is applied to an array type, the result |
| 3935 | // is the alignment of the element type. |
| 3936 | if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || |
| 3937 | ExprKind == UETT_OpenMPRequiredSimdAlign) |
| 3938 | ExprType = Context.getBaseElementType(ExprType); |
| 3939 | |
| 3940 | if (ExprKind == UETT_VecStep) |
| 3941 | return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); |
| 3942 | |
| 3943 | // Whitelist some types as extensions |
| 3944 | if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, |
| 3945 | ExprKind)) |
| 3946 | return false; |
| 3947 | |
| 3948 | if (RequireCompleteType(OpLoc, ExprType, |
| 3949 | diag::err_sizeof_alignof_incomplete_type, |
| 3950 | ExprKind, ExprRange)) |
| 3951 | return true; |
| 3952 | |
| 3953 | if (ExprType->isFunctionType()) { |
| 3954 | Diag(OpLoc, diag::err_sizeof_alignof_function_type) |
| 3955 | << ExprKind << ExprRange; |
| 3956 | return true; |
| 3957 | } |
| 3958 | |
| 3959 | if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, |
| 3960 | ExprKind)) |
| 3961 | return true; |
| 3962 | |
| 3963 | return false; |
| 3964 | } |
| 3965 | |
| 3966 | static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { |
| 3967 | E = E->IgnoreParens(); |
| 3968 | |
| 3969 | // Cannot know anything else if the expression is dependent. |
| 3970 | if (E->isTypeDependent()) |
| 3971 | return false; |
| 3972 | |
| 3973 | if (E->getObjectKind() == OK_BitField) { |
| 3974 | S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) |
| 3975 | << 1 << E->getSourceRange(); |
| 3976 | return true; |
| 3977 | } |
| 3978 | |
| 3979 | ValueDecl *D = nullptr; |
| 3980 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { |
| 3981 | D = DRE->getDecl(); |
| 3982 | } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { |
| 3983 | D = ME->getMemberDecl(); |
| 3984 | } |
| 3985 | |
| 3986 | // If it's a field, require the containing struct to have a |
| 3987 | // complete definition so that we can compute the layout. |
| 3988 | // |
| 3989 | // This can happen in C++11 onwards, either by naming the member |
| 3990 | // in a way that is not transformed into a member access expression |
| 3991 | // (in an unevaluated operand, for instance), or by naming the member |
| 3992 | // in a trailing-return-type. |
| 3993 | // |
| 3994 | // For the record, since __alignof__ on expressions is a GCC |
| 3995 | // extension, GCC seems to permit this but always gives the |
| 3996 | // nonsensical answer 0. |
| 3997 | // |
| 3998 | // We don't really need the layout here --- we could instead just |
| 3999 | // directly check for all the appropriate alignment-lowing |
| 4000 | // attributes --- but that would require duplicating a lot of |
| 4001 | // logic that just isn't worth duplicating for such a marginal |
| 4002 | // use-case. |
| 4003 | if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { |
| 4004 | // Fast path this check, since we at least know the record has a |
| 4005 | // definition if we can find a member of it. |
| 4006 | if (!FD->getParent()->isCompleteDefinition()) { |
| 4007 | S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) |
| 4008 | << E->getSourceRange(); |
| 4009 | return true; |
| 4010 | } |
| 4011 | |
| 4012 | // Otherwise, if it's a field, and the field doesn't have |
| 4013 | // reference type, then it must have a complete type (or be a |
| 4014 | // flexible array member, which we explicitly want to |
| 4015 | // white-list anyway), which makes the following checks trivial. |
| 4016 | if (!FD->getType()->isReferenceType()) |
| 4017 | return false; |
| 4018 | } |
| 4019 | |
| 4020 | return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); |
| 4021 | } |
| 4022 | |
| 4023 | bool Sema::CheckVecStepExpr(Expr *E) { |
| 4024 | E = E->IgnoreParens(); |
| 4025 | |
| 4026 | // Cannot know anything else if the expression is dependent. |
| 4027 | if (E->isTypeDependent()) |
| 4028 | return false; |
| 4029 | |
| 4030 | return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); |
| 4031 | } |
| 4032 | |
| 4033 | static void captureVariablyModifiedType(ASTContext &Context, QualType T, |
| 4034 | CapturingScopeInfo *CSI) { |
| 4035 | assert(T->isVariablyModifiedType()); |
| 4036 | assert(CSI != nullptr); |
| 4037 | |
| 4038 | // We're going to walk down into the type and look for VLA expressions. |
| 4039 | do { |
| 4040 | const Type *Ty = T.getTypePtr(); |
| 4041 | switch (Ty->getTypeClass()) { |
| 4042 | #define TYPE(Class, Base) |
| 4043 | #define ABSTRACT_TYPE(Class, Base) |
| 4044 | #define NON_CANONICAL_TYPE(Class, Base) |
| 4045 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
| 4046 | #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) |
| 4047 | #include "clang/AST/TypeNodes.def" |
| 4048 | T = QualType(); |
| 4049 | break; |
| 4050 | // These types are never variably-modified. |
| 4051 | case Type::Builtin: |
| 4052 | case Type::Complex: |
| 4053 | case Type::Vector: |
| 4054 | case Type::ExtVector: |
| 4055 | case Type::Record: |
| 4056 | case Type::Enum: |
| 4057 | case Type::Elaborated: |
| 4058 | case Type::TemplateSpecialization: |
| 4059 | case Type::ObjCObject: |
| 4060 | case Type::ObjCInterface: |
| 4061 | case Type::ObjCObjectPointer: |
| 4062 | case Type::ObjCTypeParam: |
| 4063 | case Type::Pipe: |
| 4064 | llvm_unreachable("type class is never variably-modified!" ); |
| 4065 | case Type::Adjusted: |
| 4066 | T = cast<AdjustedType>(Ty)->getOriginalType(); |
| 4067 | break; |
| 4068 | case Type::Decayed: |
| 4069 | T = cast<DecayedType>(Ty)->getPointeeType(); |
| 4070 | break; |
| 4071 | case Type::Pointer: |
| 4072 | T = cast<PointerType>(Ty)->getPointeeType(); |
| 4073 | break; |
| 4074 | case Type::BlockPointer: |
| 4075 | T = cast<BlockPointerType>(Ty)->getPointeeType(); |
| 4076 | break; |
| 4077 | case Type::LValueReference: |
| 4078 | case Type::RValueReference: |
| 4079 | T = cast<ReferenceType>(Ty)->getPointeeType(); |
| 4080 | break; |
| 4081 | case Type::MemberPointer: |
| 4082 | T = cast<MemberPointerType>(Ty)->getPointeeType(); |
| 4083 | break; |
| 4084 | case Type::ConstantArray: |
| 4085 | case Type::IncompleteArray: |
| 4086 | // Losing element qualification here is fine. |
| 4087 | T = cast<ArrayType>(Ty)->getElementType(); |
| 4088 | break; |
| 4089 | case Type::VariableArray: { |
| 4090 | // Losing element qualification here is fine. |
| 4091 | const VariableArrayType *VAT = cast<VariableArrayType>(Ty); |
| 4092 | |
| 4093 | // Unknown size indication requires no size computation. |
| 4094 | // Otherwise, evaluate and record it. |
| 4095 | auto Size = VAT->getSizeExpr(); |
| 4096 | if (Size && !CSI->isVLATypeCaptured(VAT) && |
| 4097 | (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) |
| 4098 | CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); |
| 4099 | |
| 4100 | T = VAT->getElementType(); |
| 4101 | break; |
| 4102 | } |
| 4103 | case Type::FunctionProto: |
| 4104 | case Type::FunctionNoProto: |
| 4105 | T = cast<FunctionType>(Ty)->getReturnType(); |
| 4106 | break; |
| 4107 | case Type::Paren: |
| 4108 | case Type::TypeOf: |
| 4109 | case Type::UnaryTransform: |
| 4110 | case Type::Attributed: |
| 4111 | case Type::SubstTemplateTypeParm: |
| 4112 | case Type::PackExpansion: |
| 4113 | case Type::MacroQualified: |
| 4114 | // Keep walking after single level desugaring. |
| 4115 | T = T.getSingleStepDesugaredType(Context); |
| 4116 | break; |
| 4117 | case Type::Typedef: |
| 4118 | T = cast<TypedefType>(Ty)->desugar(); |
| 4119 | break; |
| 4120 | case Type::Decltype: |
| 4121 | T = cast<DecltypeType>(Ty)->desugar(); |
| 4122 | break; |
| 4123 | case Type::Auto: |
| 4124 | case Type::DeducedTemplateSpecialization: |
| 4125 | T = cast<DeducedType>(Ty)->getDeducedType(); |
| 4126 | break; |
| 4127 | case Type::TypeOfExpr: |
| 4128 | T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); |
| 4129 | break; |
| 4130 | case Type::Atomic: |
| 4131 | T = cast<AtomicType>(Ty)->getValueType(); |
| 4132 | break; |
| 4133 | } |
| 4134 | } while (!T.isNull() && T->isVariablyModifiedType()); |
| 4135 | } |
| 4136 | |
| 4137 | /// Build a sizeof or alignof expression given a type operand. |
| 4138 | ExprResult |
| 4139 | Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, |
| 4140 | SourceLocation OpLoc, |
| 4141 | UnaryExprOrTypeTrait ExprKind, |
| 4142 | SourceRange R) { |
| 4143 | if (!TInfo) |
| 4144 | return ExprError(); |
| 4145 | |
| 4146 | QualType T = TInfo->getType(); |
| 4147 | |
| 4148 | if (!T->isDependentType() && |
| 4149 | CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) |
| 4150 | return ExprError(); |
| 4151 | |
| 4152 | if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { |
| 4153 | if (auto *TT = T->getAs<TypedefType>()) { |
| 4154 | for (auto I = FunctionScopes.rbegin(), |
| 4155 | E = std::prev(FunctionScopes.rend()); |
| 4156 | I != E; ++I) { |
| 4157 | auto *CSI = dyn_cast<CapturingScopeInfo>(*I); |
| 4158 | if (CSI == nullptr) |
| 4159 | break; |
| 4160 | DeclContext *DC = nullptr; |
| 4161 | if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) |
| 4162 | DC = LSI->CallOperator; |
| 4163 | else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) |
| 4164 | DC = CRSI->TheCapturedDecl; |
| 4165 | else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) |
| 4166 | DC = BSI->TheDecl; |
| 4167 | if (DC) { |
| 4168 | if (DC->containsDecl(TT->getDecl())) |
| 4169 | break; |
| 4170 | captureVariablyModifiedType(Context, T, CSI); |
| 4171 | } |
| 4172 | } |
| 4173 | } |
| 4174 | } |
| 4175 | |
| 4176 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
| 4177 | return new (Context) UnaryExprOrTypeTraitExpr( |
| 4178 | ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); |
| 4179 | } |
| 4180 | |
| 4181 | /// Build a sizeof or alignof expression given an expression |
| 4182 | /// operand. |
| 4183 | ExprResult |
| 4184 | Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, |
| 4185 | UnaryExprOrTypeTrait ExprKind) { |
| 4186 | ExprResult PE = CheckPlaceholderExpr(E); |
| 4187 | if (PE.isInvalid()) |
| 4188 | return ExprError(); |
| 4189 | |
| 4190 | E = PE.get(); |
| 4191 | |
| 4192 | // Verify that the operand is valid. |
| 4193 | bool isInvalid = false; |
| 4194 | if (E->isTypeDependent()) { |
| 4195 | // Delay type-checking for type-dependent expressions. |
| 4196 | } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { |
| 4197 | isInvalid = CheckAlignOfExpr(*this, E, ExprKind); |
| 4198 | } else if (ExprKind == UETT_VecStep) { |
| 4199 | isInvalid = CheckVecStepExpr(E); |
| 4200 | } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { |
| 4201 | Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); |
| 4202 | isInvalid = true; |
| 4203 | } else if (E->refersToBitField()) { // C99 6.5.3.4p1. |
| 4204 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; |
| 4205 | isInvalid = true; |
| 4206 | } else { |
| 4207 | isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); |
| 4208 | } |
| 4209 | |
| 4210 | if (isInvalid) |
| 4211 | return ExprError(); |
| 4212 | |
| 4213 | if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { |
| 4214 | PE = TransformToPotentiallyEvaluated(E); |
| 4215 | if (PE.isInvalid()) return ExprError(); |
| 4216 | E = PE.get(); |
| 4217 | } |
| 4218 | |
| 4219 | // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. |
| 4220 | return new (Context) UnaryExprOrTypeTraitExpr( |
| 4221 | ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); |
| 4222 | } |
| 4223 | |
| 4224 | /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c |
| 4225 | /// expr and the same for @c alignof and @c __alignof |
| 4226 | /// Note that the ArgRange is invalid if isType is false. |
| 4227 | ExprResult |
| 4228 | Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, |
| 4229 | UnaryExprOrTypeTrait ExprKind, bool IsType, |
| 4230 | void *TyOrEx, SourceRange ArgRange) { |
| 4231 | // If error parsing type, ignore. |
| 4232 | if (!TyOrEx) return ExprError(); |
| 4233 | |
| 4234 | if (IsType) { |
| 4235 | TypeSourceInfo *TInfo; |
| 4236 | (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); |
| 4237 | return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); |
| 4238 | } |
| 4239 | |
| 4240 | Expr *ArgEx = (Expr *)TyOrEx; |
| 4241 | ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); |
| 4242 | return Result; |
| 4243 | } |
| 4244 | |
| 4245 | static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, |
| 4246 | bool IsReal) { |
| 4247 | if (V.get()->isTypeDependent()) |
| 4248 | return S.Context.DependentTy; |
| 4249 | |
| 4250 | // _Real and _Imag are only l-values for normal l-values. |
| 4251 | if (V.get()->getObjectKind() != OK_Ordinary) { |
| 4252 | V = S.DefaultLvalueConversion(V.get()); |
| 4253 | if (V.isInvalid()) |
| 4254 | return QualType(); |
| 4255 | } |
| 4256 | |
| 4257 | // These operators return the element type of a complex type. |
| 4258 | if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) |
| 4259 | return CT->getElementType(); |
| 4260 | |
| 4261 | // Otherwise they pass through real integer and floating point types here. |
| 4262 | if (V.get()->getType()->isArithmeticType()) |
| 4263 | return V.get()->getType(); |
| 4264 | |
| 4265 | // Test for placeholders. |
| 4266 | ExprResult PR = S.CheckPlaceholderExpr(V.get()); |
| 4267 | if (PR.isInvalid()) return QualType(); |
| 4268 | if (PR.get() != V.get()) { |
| 4269 | V = PR; |
| 4270 | return CheckRealImagOperand(S, V, Loc, IsReal); |
| 4271 | } |
| 4272 | |
| 4273 | // Reject anything else. |
| 4274 | S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() |
| 4275 | << (IsReal ? "__real" : "__imag" ); |
| 4276 | return QualType(); |
| 4277 | } |
| 4278 | |
| 4279 | |
| 4280 | |
| 4281 | ExprResult |
| 4282 | Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, |
| 4283 | tok::TokenKind Kind, Expr *Input) { |
| 4284 | UnaryOperatorKind Opc; |
| 4285 | switch (Kind) { |
| 4286 | default: llvm_unreachable("Unknown unary op!" ); |
| 4287 | case tok::plusplus: Opc = UO_PostInc; break; |
| 4288 | case tok::minusminus: Opc = UO_PostDec; break; |
| 4289 | } |
| 4290 | |
| 4291 | // Since this might is a postfix expression, get rid of ParenListExprs. |
| 4292 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); |
| 4293 | if (Result.isInvalid()) return ExprError(); |
| 4294 | Input = Result.get(); |
| 4295 | |
| 4296 | return BuildUnaryOp(S, OpLoc, Opc, Input); |
| 4297 | } |
| 4298 | |
| 4299 | /// Diagnose if arithmetic on the given ObjC pointer is illegal. |
| 4300 | /// |
| 4301 | /// \return true on error |
| 4302 | static bool checkArithmeticOnObjCPointer(Sema &S, |
| 4303 | SourceLocation opLoc, |
| 4304 | Expr *op) { |
| 4305 | assert(op->getType()->isObjCObjectPointerType()); |
| 4306 | if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && |
| 4307 | !S.LangOpts.ObjCSubscriptingLegacyRuntime) |
| 4308 | return false; |
| 4309 | |
| 4310 | S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) |
| 4311 | << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() |
| 4312 | << op->getSourceRange(); |
| 4313 | return true; |
| 4314 | } |
| 4315 | |
| 4316 | static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { |
| 4317 | auto *BaseNoParens = Base->IgnoreParens(); |
| 4318 | if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) |
| 4319 | return MSProp->getPropertyDecl()->getType()->isArrayType(); |
| 4320 | return isa<MSPropertySubscriptExpr>(BaseNoParens); |
| 4321 | } |
| 4322 | |
| 4323 | ExprResult |
| 4324 | Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, |
| 4325 | Expr *idx, SourceLocation rbLoc) { |
| 4326 | if (base && !base->getType().isNull() && |
| 4327 | base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) |
| 4328 | return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), |
| 4329 | /*Length=*/nullptr, rbLoc); |
| 4330 | |
| 4331 | // Since this might be a postfix expression, get rid of ParenListExprs. |
| 4332 | if (isa<ParenListExpr>(base)) { |
| 4333 | ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); |
| 4334 | if (result.isInvalid()) return ExprError(); |
| 4335 | base = result.get(); |
| 4336 | } |
| 4337 | |
| 4338 | // Handle any non-overload placeholder types in the base and index |
| 4339 | // expressions. We can't handle overloads here because the other |
| 4340 | // operand might be an overloadable type, in which case the overload |
| 4341 | // resolution for the operator overload should get the first crack |
| 4342 | // at the overload. |
| 4343 | bool IsMSPropertySubscript = false; |
| 4344 | if (base->getType()->isNonOverloadPlaceholderType()) { |
| 4345 | IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); |
| 4346 | if (!IsMSPropertySubscript) { |
| 4347 | ExprResult result = CheckPlaceholderExpr(base); |
| 4348 | if (result.isInvalid()) |
| 4349 | return ExprError(); |
| 4350 | base = result.get(); |
| 4351 | } |
| 4352 | } |
| 4353 | if (idx->getType()->isNonOverloadPlaceholderType()) { |
| 4354 | ExprResult result = CheckPlaceholderExpr(idx); |
| 4355 | if (result.isInvalid()) return ExprError(); |
| 4356 | idx = result.get(); |
| 4357 | } |
| 4358 | |
| 4359 | // Build an unanalyzed expression if either operand is type-dependent. |
| 4360 | if (getLangOpts().CPlusPlus && |
| 4361 | (base->isTypeDependent() || idx->isTypeDependent())) { |
| 4362 | return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, |
| 4363 | VK_LValue, OK_Ordinary, rbLoc); |
| 4364 | } |
| 4365 | |
| 4366 | // MSDN, property (C++) |
| 4367 | // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx |
| 4368 | // This attribute can also be used in the declaration of an empty array in a |
| 4369 | // class or structure definition. For example: |
| 4370 | // __declspec(property(get=GetX, put=PutX)) int x[]; |
| 4371 | // The above statement indicates that x[] can be used with one or more array |
| 4372 | // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), |
| 4373 | // and p->x[a][b] = i will be turned into p->PutX(a, b, i); |
| 4374 | if (IsMSPropertySubscript) { |
| 4375 | // Build MS property subscript expression if base is MS property reference |
| 4376 | // or MS property subscript. |
| 4377 | return new (Context) MSPropertySubscriptExpr( |
| 4378 | base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); |
| 4379 | } |
| 4380 | |
| 4381 | // Use C++ overloaded-operator rules if either operand has record |
| 4382 | // type. The spec says to do this if either type is *overloadable*, |
| 4383 | // but enum types can't declare subscript operators or conversion |
| 4384 | // operators, so there's nothing interesting for overload resolution |
| 4385 | // to do if there aren't any record types involved. |
| 4386 | // |
| 4387 | // ObjC pointers have their own subscripting logic that is not tied |
| 4388 | // to overload resolution and so should not take this path. |
| 4389 | if (getLangOpts().CPlusPlus && |
| 4390 | (base->getType()->isRecordType() || |
| 4391 | (!base->getType()->isObjCObjectPointerType() && |
| 4392 | idx->getType()->isRecordType()))) { |
| 4393 | return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); |
| 4394 | } |
| 4395 | |
| 4396 | ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); |
| 4397 | |
| 4398 | if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) |
| 4399 | CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); |
| 4400 | |
| 4401 | return Res; |
| 4402 | } |
| 4403 | |
| 4404 | void Sema::CheckAddressOfNoDeref(const Expr *E) { |
| 4405 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
| 4406 | const Expr *StrippedExpr = E->IgnoreParenImpCasts(); |
| 4407 | |
| 4408 | // For expressions like `&(*s).b`, the base is recorded and what should be |
| 4409 | // checked. |
| 4410 | const MemberExpr *Member = nullptr; |
| 4411 | while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) |
| 4412 | StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); |
| 4413 | |
| 4414 | LastRecord.PossibleDerefs.erase(StrippedExpr); |
| 4415 | } |
| 4416 | |
| 4417 | void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { |
| 4418 | QualType ResultTy = E->getType(); |
| 4419 | ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); |
| 4420 | |
| 4421 | // Bail if the element is an array since it is not memory access. |
| 4422 | if (isa<ArrayType>(ResultTy)) |
| 4423 | return; |
| 4424 | |
| 4425 | if (ResultTy->hasAttr(attr::NoDeref)) { |
| 4426 | LastRecord.PossibleDerefs.insert(E); |
| 4427 | return; |
| 4428 | } |
| 4429 | |
| 4430 | // Check if the base type is a pointer to a member access of a struct |
| 4431 | // marked with noderef. |
| 4432 | const Expr *Base = E->getBase(); |
| 4433 | QualType BaseTy = Base->getType(); |
| 4434 | if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) |
| 4435 | // Not a pointer access |
| 4436 | return; |
| 4437 | |
| 4438 | const MemberExpr *Member = nullptr; |
| 4439 | while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && |
| 4440 | Member->isArrow()) |
| 4441 | Base = Member->getBase(); |
| 4442 | |
| 4443 | if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { |
| 4444 | if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) |
| 4445 | LastRecord.PossibleDerefs.insert(E); |
| 4446 | } |
| 4447 | } |
| 4448 | |
| 4449 | ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, |
| 4450 | Expr *LowerBound, |
| 4451 | SourceLocation ColonLoc, Expr *Length, |
| 4452 | SourceLocation RBLoc) { |
| 4453 | if (Base->getType()->isPlaceholderType() && |
| 4454 | !Base->getType()->isSpecificPlaceholderType( |
| 4455 | BuiltinType::OMPArraySection)) { |
| 4456 | ExprResult Result = CheckPlaceholderExpr(Base); |
| 4457 | if (Result.isInvalid()) |
| 4458 | return ExprError(); |
| 4459 | Base = Result.get(); |
| 4460 | } |
| 4461 | if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { |
| 4462 | ExprResult Result = CheckPlaceholderExpr(LowerBound); |
| 4463 | if (Result.isInvalid()) |
| 4464 | return ExprError(); |
| 4465 | Result = DefaultLvalueConversion(Result.get()); |
| 4466 | if (Result.isInvalid()) |
| 4467 | return ExprError(); |
| 4468 | LowerBound = Result.get(); |
| 4469 | } |
| 4470 | if (Length && Length->getType()->isNonOverloadPlaceholderType()) { |
| 4471 | ExprResult Result = CheckPlaceholderExpr(Length); |
| 4472 | if (Result.isInvalid()) |
| 4473 | return ExprError(); |
| 4474 | Result = DefaultLvalueConversion(Result.get()); |
| 4475 | if (Result.isInvalid()) |
| 4476 | return ExprError(); |
| 4477 | Length = Result.get(); |
| 4478 | } |
| 4479 | |
| 4480 | // Build an unanalyzed expression if either operand is type-dependent. |
| 4481 | if (Base->isTypeDependent() || |
| 4482 | (LowerBound && |
| 4483 | (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || |
| 4484 | (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { |
| 4485 | return new (Context) |
| 4486 | OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, |
| 4487 | VK_LValue, OK_Ordinary, ColonLoc, RBLoc); |
| 4488 | } |
| 4489 | |
| 4490 | // Perform default conversions. |
| 4491 | QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); |
| 4492 | QualType ResultTy; |
| 4493 | if (OriginalTy->isAnyPointerType()) { |
| 4494 | ResultTy = OriginalTy->getPointeeType(); |
| 4495 | } else if (OriginalTy->isArrayType()) { |
| 4496 | ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); |
| 4497 | } else { |
| 4498 | return ExprError( |
| 4499 | Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) |
| 4500 | << Base->getSourceRange()); |
| 4501 | } |
| 4502 | // C99 6.5.2.1p1 |
| 4503 | if (LowerBound) { |
| 4504 | auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), |
| 4505 | LowerBound); |
| 4506 | if (Res.isInvalid()) |
| 4507 | return ExprError(Diag(LowerBound->getExprLoc(), |
| 4508 | diag::err_omp_typecheck_section_not_integer) |
| 4509 | << 0 << LowerBound->getSourceRange()); |
| 4510 | LowerBound = Res.get(); |
| 4511 | |
| 4512 | if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || |
| 4513 | LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) |
| 4514 | Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) |
| 4515 | << 0 << LowerBound->getSourceRange(); |
| 4516 | } |
| 4517 | if (Length) { |
| 4518 | auto Res = |
| 4519 | PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); |
| 4520 | if (Res.isInvalid()) |
| 4521 | return ExprError(Diag(Length->getExprLoc(), |
| 4522 | diag::err_omp_typecheck_section_not_integer) |
| 4523 | << 1 << Length->getSourceRange()); |
| 4524 | Length = Res.get(); |
| 4525 | |
| 4526 | if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || |
| 4527 | Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) |
| 4528 | Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) |
| 4529 | << 1 << Length->getSourceRange(); |
| 4530 | } |
| 4531 | |
| 4532 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, |
| 4533 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object |
| 4534 | // type. Note that functions are not objects, and that (in C99 parlance) |
| 4535 | // incomplete types are not object types. |
| 4536 | if (ResultTy->isFunctionType()) { |
| 4537 | Diag(Base->getExprLoc(), diag::err_omp_section_function_type) |
| 4538 | << ResultTy << Base->getSourceRange(); |
| 4539 | return ExprError(); |
| 4540 | } |
| 4541 | |
| 4542 | if (RequireCompleteType(Base->getExprLoc(), ResultTy, |
| 4543 | diag::err_omp_section_incomplete_type, Base)) |
| 4544 | return ExprError(); |
| 4545 | |
| 4546 | if (LowerBound && !OriginalTy->isAnyPointerType()) { |
| 4547 | Expr::EvalResult Result; |
| 4548 | if (LowerBound->EvaluateAsInt(Result, Context)) { |
| 4549 | // OpenMP 4.5, [2.4 Array Sections] |
| 4550 | // The array section must be a subset of the original array. |
| 4551 | llvm::APSInt LowerBoundValue = Result.Val.getInt(); |
| 4552 | if (LowerBoundValue.isNegative()) { |
| 4553 | Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) |
| 4554 | << LowerBound->getSourceRange(); |
| 4555 | return ExprError(); |
| 4556 | } |
| 4557 | } |
| 4558 | } |
| 4559 | |
| 4560 | if (Length) { |
| 4561 | Expr::EvalResult Result; |
| 4562 | if (Length->EvaluateAsInt(Result, Context)) { |
| 4563 | // OpenMP 4.5, [2.4 Array Sections] |
| 4564 | // The length must evaluate to non-negative integers. |
| 4565 | llvm::APSInt LengthValue = Result.Val.getInt(); |
| 4566 | if (LengthValue.isNegative()) { |
| 4567 | Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) |
| 4568 | << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) |
| 4569 | << Length->getSourceRange(); |
| 4570 | return ExprError(); |
| 4571 | } |
| 4572 | } |
| 4573 | } else if (ColonLoc.isValid() && |
| 4574 | (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && |
| 4575 | !OriginalTy->isVariableArrayType()))) { |
| 4576 | // OpenMP 4.5, [2.4 Array Sections] |
| 4577 | // When the size of the array dimension is not known, the length must be |
| 4578 | // specified explicitly. |
| 4579 | Diag(ColonLoc, diag::err_omp_section_length_undefined) |
| 4580 | << (!OriginalTy.isNull() && OriginalTy->isArrayType()); |
| 4581 | return ExprError(); |
| 4582 | } |
| 4583 | |
| 4584 | if (!Base->getType()->isSpecificPlaceholderType( |
| 4585 | BuiltinType::OMPArraySection)) { |
| 4586 | ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); |
| 4587 | if (Result.isInvalid()) |
| 4588 | return ExprError(); |
| 4589 | Base = Result.get(); |
| 4590 | } |
| 4591 | return new (Context) |
| 4592 | OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, |
| 4593 | VK_LValue, OK_Ordinary, ColonLoc, RBLoc); |
| 4594 | } |
| 4595 | |
| 4596 | ExprResult |
| 4597 | Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, |
| 4598 | Expr *Idx, SourceLocation RLoc) { |
| 4599 | Expr *LHSExp = Base; |
| 4600 | Expr *RHSExp = Idx; |
| 4601 | |
| 4602 | ExprValueKind VK = VK_LValue; |
| 4603 | ExprObjectKind OK = OK_Ordinary; |
| 4604 | |
| 4605 | // Per C++ core issue 1213, the result is an xvalue if either operand is |
| 4606 | // a non-lvalue array, and an lvalue otherwise. |
| 4607 | if (getLangOpts().CPlusPlus11) { |
| 4608 | for (auto *Op : {LHSExp, RHSExp}) { |
| 4609 | Op = Op->IgnoreImplicit(); |
| 4610 | if (Op->getType()->isArrayType() && !Op->isLValue()) |
| 4611 | VK = VK_XValue; |
| 4612 | } |
| 4613 | } |
| 4614 | |
| 4615 | // Perform default conversions. |
| 4616 | if (!LHSExp->getType()->getAs<VectorType>()) { |
| 4617 | ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); |
| 4618 | if (Result.isInvalid()) |
| 4619 | return ExprError(); |
| 4620 | LHSExp = Result.get(); |
| 4621 | } |
| 4622 | ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); |
| 4623 | if (Result.isInvalid()) |
| 4624 | return ExprError(); |
| 4625 | RHSExp = Result.get(); |
| 4626 | |
| 4627 | QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); |
| 4628 | |
| 4629 | // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent |
| 4630 | // to the expression *((e1)+(e2)). This means the array "Base" may actually be |
| 4631 | // in the subscript position. As a result, we need to derive the array base |
| 4632 | // and index from the expression types. |
| 4633 | Expr *BaseExpr, *IndexExpr; |
| 4634 | QualType ResultType; |
| 4635 | if (LHSTy->isDependentType() || RHSTy->isDependentType()) { |
| 4636 | BaseExpr = LHSExp; |
| 4637 | IndexExpr = RHSExp; |
| 4638 | ResultType = Context.DependentTy; |
| 4639 | } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { |
| 4640 | BaseExpr = LHSExp; |
| 4641 | IndexExpr = RHSExp; |
| 4642 | ResultType = PTy->getPointeeType(); |
| 4643 | } else if (const ObjCObjectPointerType *PTy = |
| 4644 | LHSTy->getAs<ObjCObjectPointerType>()) { |
| 4645 | BaseExpr = LHSExp; |
| 4646 | IndexExpr = RHSExp; |
| 4647 | |
| 4648 | // Use custom logic if this should be the pseudo-object subscript |
| 4649 | // expression. |
| 4650 | if (!LangOpts.isSubscriptPointerArithmetic()) |
| 4651 | return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, |
| 4652 | nullptr); |
| 4653 | |
| 4654 | ResultType = PTy->getPointeeType(); |
| 4655 | } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { |
| 4656 | // Handle the uncommon case of "123[Ptr]". |
| 4657 | BaseExpr = RHSExp; |
| 4658 | IndexExpr = LHSExp; |
| 4659 | ResultType = PTy->getPointeeType(); |
| 4660 | } else if (const ObjCObjectPointerType *PTy = |
| 4661 | RHSTy->getAs<ObjCObjectPointerType>()) { |
| 4662 | // Handle the uncommon case of "123[Ptr]". |
| 4663 | BaseExpr = RHSExp; |
| 4664 | IndexExpr = LHSExp; |
| 4665 | ResultType = PTy->getPointeeType(); |
| 4666 | if (!LangOpts.isSubscriptPointerArithmetic()) { |
| 4667 | Diag(LLoc, diag::err_subscript_nonfragile_interface) |
| 4668 | << ResultType << BaseExpr->getSourceRange(); |
| 4669 | return ExprError(); |
| 4670 | } |
| 4671 | } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { |
| 4672 | BaseExpr = LHSExp; // vectors: V[123] |
| 4673 | IndexExpr = RHSExp; |
| 4674 | // We apply C++ DR1213 to vector subscripting too. |
| 4675 | if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { |
| 4676 | ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); |
| 4677 | if (Materialized.isInvalid()) |
| 4678 | return ExprError(); |
| 4679 | LHSExp = Materialized.get(); |
| 4680 | } |
| 4681 | VK = LHSExp->getValueKind(); |
| 4682 | if (VK != VK_RValue) |
| 4683 | OK = OK_VectorComponent; |
| 4684 | |
| 4685 | ResultType = VTy->getElementType(); |
| 4686 | QualType BaseType = BaseExpr->getType(); |
| 4687 | Qualifiers BaseQuals = BaseType.getQualifiers(); |
| 4688 | Qualifiers MemberQuals = ResultType.getQualifiers(); |
| 4689 | Qualifiers Combined = BaseQuals + MemberQuals; |
| 4690 | if (Combined != MemberQuals) |
| 4691 | ResultType = Context.getQualifiedType(ResultType, Combined); |
| 4692 | } else if (LHSTy->isArrayType()) { |
| 4693 | // If we see an array that wasn't promoted by |
| 4694 | // DefaultFunctionArrayLvalueConversion, it must be an array that |
| 4695 | // wasn't promoted because of the C90 rule that doesn't |
| 4696 | // allow promoting non-lvalue arrays. Warn, then |
| 4697 | // force the promotion here. |
| 4698 | Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) |
| 4699 | << LHSExp->getSourceRange(); |
| 4700 | LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), |
| 4701 | CK_ArrayToPointerDecay).get(); |
| 4702 | LHSTy = LHSExp->getType(); |
| 4703 | |
| 4704 | BaseExpr = LHSExp; |
| 4705 | IndexExpr = RHSExp; |
| 4706 | ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); |
| 4707 | } else if (RHSTy->isArrayType()) { |
| 4708 | // Same as previous, except for 123[f().a] case |
| 4709 | Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) |
| 4710 | << RHSExp->getSourceRange(); |
| 4711 | RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), |
| 4712 | CK_ArrayToPointerDecay).get(); |
| 4713 | RHSTy = RHSExp->getType(); |
| 4714 | |
| 4715 | BaseExpr = RHSExp; |
| 4716 | IndexExpr = LHSExp; |
| 4717 | ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); |
| 4718 | } else { |
| 4719 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) |
| 4720 | << LHSExp->getSourceRange() << RHSExp->getSourceRange()); |
| 4721 | } |
| 4722 | // C99 6.5.2.1p1 |
| 4723 | if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) |
| 4724 | return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) |
| 4725 | << IndexExpr->getSourceRange()); |
| 4726 | |
| 4727 | if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || |
| 4728 | IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) |
| 4729 | && !IndexExpr->isTypeDependent()) |
| 4730 | Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); |
| 4731 | |
| 4732 | // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, |
| 4733 | // C++ [expr.sub]p1: The type "T" shall be a completely-defined object |
| 4734 | // type. Note that Functions are not objects, and that (in C99 parlance) |
| 4735 | // incomplete types are not object types. |
| 4736 | if (ResultType->isFunctionType()) { |
| 4737 | Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) |
| 4738 | << ResultType << BaseExpr->getSourceRange(); |
| 4739 | return ExprError(); |
| 4740 | } |
| 4741 | |
| 4742 | if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { |
| 4743 | // GNU extension: subscripting on pointer to void |
| 4744 | Diag(LLoc, diag::ext_gnu_subscript_void_type) |
| 4745 | << BaseExpr->getSourceRange(); |
| 4746 | |
| 4747 | // C forbids expressions of unqualified void type from being l-values. |
| 4748 | // See IsCForbiddenLValueType. |
| 4749 | if (!ResultType.hasQualifiers()) VK = VK_RValue; |
| 4750 | } else if (!ResultType->isDependentType() && |
| 4751 | RequireCompleteType(LLoc, ResultType, |
| 4752 | diag::err_subscript_incomplete_type, BaseExpr)) |
| 4753 | return ExprError(); |
| 4754 | |
| 4755 | assert(VK == VK_RValue || LangOpts.CPlusPlus || |
| 4756 | !ResultType.isCForbiddenLValueType()); |
| 4757 | |
| 4758 | return new (Context) |
| 4759 | ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); |
| 4760 | } |
| 4761 | |
| 4762 | bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, |
| 4763 | ParmVarDecl *Param) { |
| 4764 | if (Param->hasUnparsedDefaultArg()) { |
| 4765 | Diag(CallLoc, |
| 4766 | diag::err_use_of_default_argument_to_function_declared_later) << |
| 4767 | FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); |
| 4768 | Diag(UnparsedDefaultArgLocs[Param], |
| 4769 | diag::note_default_argument_declared_here); |
| 4770 | return true; |
| 4771 | } |
| 4772 | |
| 4773 | if (Param->hasUninstantiatedDefaultArg()) { |
| 4774 | Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); |
| 4775 | |
| 4776 | EnterExpressionEvaluationContext EvalContext( |
| 4777 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); |
| 4778 | |
| 4779 | // Instantiate the expression. |
| 4780 | // |
| 4781 | // FIXME: Pass in a correct Pattern argument, otherwise |
| 4782 | // getTemplateInstantiationArgs uses the lexical context of FD, e.g. |
| 4783 | // |
| 4784 | // template<typename T> |
| 4785 | // struct A { |
| 4786 | // static int FooImpl(); |
| 4787 | // |
| 4788 | // template<typename Tp> |
| 4789 | // // bug: default argument A<T>::FooImpl() is evaluated with 2-level |
| 4790 | // // template argument list [[T], [Tp]], should be [[Tp]]. |
| 4791 | // friend A<Tp> Foo(int a); |
| 4792 | // }; |
| 4793 | // |
| 4794 | // template<typename T> |
| 4795 | // A<T> Foo(int a = A<T>::FooImpl()); |
| 4796 | MultiLevelTemplateArgumentList MutiLevelArgList |
| 4797 | = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); |
| 4798 | |
| 4799 | InstantiatingTemplate Inst(*this, CallLoc, Param, |
| 4800 | MutiLevelArgList.getInnermost()); |
| 4801 | if (Inst.isInvalid()) |
| 4802 | return true; |
| 4803 | if (Inst.isAlreadyInstantiating()) { |
| 4804 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; |
| 4805 | Param->setInvalidDecl(); |
| 4806 | return true; |
| 4807 | } |
| 4808 | |
| 4809 | ExprResult Result; |
| 4810 | { |
| 4811 | // C++ [dcl.fct.default]p5: |
| 4812 | // The names in the [default argument] expression are bound, and |
| 4813 | // the semantic constraints are checked, at the point where the |
| 4814 | // default argument expression appears. |
| 4815 | ContextRAII SavedContext(*this, FD); |
| 4816 | LocalInstantiationScope Local(*this); |
| 4817 | Result = SubstInitializer(UninstExpr, MutiLevelArgList, |
| 4818 | /*DirectInit*/false); |
| 4819 | } |
| 4820 | if (Result.isInvalid()) |
| 4821 | return true; |
| 4822 | |
| 4823 | // Check the expression as an initializer for the parameter. |
| 4824 | InitializedEntity Entity |
| 4825 | = InitializedEntity::InitializeParameter(Context, Param); |
| 4826 | InitializationKind Kind = InitializationKind::CreateCopy( |
| 4827 | Param->getLocation(), |
| 4828 | /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); |
| 4829 | Expr *ResultE = Result.getAs<Expr>(); |
| 4830 | |
| 4831 | InitializationSequence InitSeq(*this, Entity, Kind, ResultE); |
| 4832 | Result = InitSeq.Perform(*this, Entity, Kind, ResultE); |
| 4833 | if (Result.isInvalid()) |
| 4834 | return true; |
| 4835 | |
| 4836 | Result = |
| 4837 | ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), |
| 4838 | /*DiscardedValue*/ false); |
| 4839 | if (Result.isInvalid()) |
| 4840 | return true; |
| 4841 | |
| 4842 | // Remember the instantiated default argument. |
| 4843 | Param->setDefaultArg(Result.getAs<Expr>()); |
| 4844 | if (ASTMutationListener *L = getASTMutationListener()) { |
| 4845 | L->DefaultArgumentInstantiated(Param); |
| 4846 | } |
| 4847 | } |
| 4848 | |
| 4849 | // If the default argument expression is not set yet, we are building it now. |
| 4850 | if (!Param->hasInit()) { |
| 4851 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; |
| 4852 | Param->setInvalidDecl(); |
| 4853 | return true; |
| 4854 | } |
| 4855 | |
| 4856 | // If the default expression creates temporaries, we need to |
| 4857 | // push them to the current stack of expression temporaries so they'll |
| 4858 | // be properly destroyed. |
| 4859 | // FIXME: We should really be rebuilding the default argument with new |
| 4860 | // bound temporaries; see the comment in PR5810. |
| 4861 | // We don't need to do that with block decls, though, because |
| 4862 | // blocks in default argument expression can never capture anything. |
| 4863 | if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { |
| 4864 | // Set the "needs cleanups" bit regardless of whether there are |
| 4865 | // any explicit objects. |
| 4866 | Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); |
| 4867 | |
| 4868 | // Append all the objects to the cleanup list. Right now, this |
| 4869 | // should always be a no-op, because blocks in default argument |
| 4870 | // expressions should never be able to capture anything. |
| 4871 | assert(!Init->getNumObjects() && |
| 4872 | "default argument expression has capturing blocks?" ); |
| 4873 | } |
| 4874 | |
| 4875 | // We already type-checked the argument, so we know it works. |
| 4876 | // Just mark all of the declarations in this potentially-evaluated expression |
| 4877 | // as being "referenced". |
| 4878 | EnterExpressionEvaluationContext EvalContext( |
| 4879 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); |
| 4880 | MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), |
| 4881 | /*SkipLocalVariables=*/true); |
| 4882 | return false; |
| 4883 | } |
| 4884 | |
| 4885 | ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, |
| 4886 | FunctionDecl *FD, ParmVarDecl *Param) { |
| 4887 | if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) |
| 4888 | return ExprError(); |
| 4889 | return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); |
| 4890 | } |
| 4891 | |
| 4892 | Sema::VariadicCallType |
| 4893 | Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, |
| 4894 | Expr *Fn) { |
| 4895 | if (Proto && Proto->isVariadic()) { |
| 4896 | if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) |
| 4897 | return VariadicConstructor; |
| 4898 | else if (Fn && Fn->getType()->isBlockPointerType()) |
| 4899 | return VariadicBlock; |
| 4900 | else if (FDecl) { |
| 4901 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) |
| 4902 | if (Method->isInstance()) |
| 4903 | return VariadicMethod; |
| 4904 | } else if (Fn && Fn->getType() == Context.BoundMemberTy) |
| 4905 | return VariadicMethod; |
| 4906 | return VariadicFunction; |
| 4907 | } |
| 4908 | return VariadicDoesNotApply; |
| 4909 | } |
| 4910 | |
| 4911 | namespace { |
| 4912 | class FunctionCallCCC final : public FunctionCallFilterCCC { |
| 4913 | public: |
| 4914 | FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, |
| 4915 | unsigned NumArgs, MemberExpr *ME) |
| 4916 | : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), |
| 4917 | FunctionName(FuncName) {} |
| 4918 | |
| 4919 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
| 4920 | if (!candidate.getCorrectionSpecifier() || |
| 4921 | candidate.getCorrectionAsIdentifierInfo() != FunctionName) { |
| 4922 | return false; |
| 4923 | } |
| 4924 | |
| 4925 | return FunctionCallFilterCCC::ValidateCandidate(candidate); |
| 4926 | } |
| 4927 | |
| 4928 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
| 4929 | return llvm::make_unique<FunctionCallCCC>(*this); |
| 4930 | } |
| 4931 | |
| 4932 | private: |
| 4933 | const IdentifierInfo *const FunctionName; |
| 4934 | }; |
| 4935 | } |
| 4936 | |
| 4937 | static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, |
| 4938 | FunctionDecl *FDecl, |
| 4939 | ArrayRef<Expr *> Args) { |
| 4940 | MemberExpr *ME = dyn_cast<MemberExpr>(Fn); |
| 4941 | DeclarationName FuncName = FDecl->getDeclName(); |
| 4942 | SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); |
| 4943 | |
| 4944 | FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); |
| 4945 | if (TypoCorrection Corrected = S.CorrectTypo( |
| 4946 | DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, |
| 4947 | S.getScopeForContext(S.CurContext), nullptr, CCC, |
| 4948 | Sema::CTK_ErrorRecovery)) { |
| 4949 | if (NamedDecl *ND = Corrected.getFoundDecl()) { |
| 4950 | if (Corrected.isOverloaded()) { |
| 4951 | OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); |
| 4952 | OverloadCandidateSet::iterator Best; |
| 4953 | for (NamedDecl *CD : Corrected) { |
| 4954 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) |
| 4955 | S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, |
| 4956 | OCS); |
| 4957 | } |
| 4958 | switch (OCS.BestViableFunction(S, NameLoc, Best)) { |
| 4959 | case OR_Success: |
| 4960 | ND = Best->FoundDecl; |
| 4961 | Corrected.setCorrectionDecl(ND); |
| 4962 | break; |
| 4963 | default: |
| 4964 | break; |
| 4965 | } |
| 4966 | } |
| 4967 | ND = ND->getUnderlyingDecl(); |
| 4968 | if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) |
| 4969 | return Corrected; |
| 4970 | } |
| 4971 | } |
| 4972 | return TypoCorrection(); |
| 4973 | } |
| 4974 | |
| 4975 | /// ConvertArgumentsForCall - Converts the arguments specified in |
| 4976 | /// Args/NumArgs to the parameter types of the function FDecl with |
| 4977 | /// function prototype Proto. Call is the call expression itself, and |
| 4978 | /// Fn is the function expression. For a C++ member function, this |
| 4979 | /// routine does not attempt to convert the object argument. Returns |
| 4980 | /// true if the call is ill-formed. |
| 4981 | bool |
| 4982 | Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, |
| 4983 | FunctionDecl *FDecl, |
| 4984 | const FunctionProtoType *Proto, |
| 4985 | ArrayRef<Expr *> Args, |
| 4986 | SourceLocation RParenLoc, |
| 4987 | bool IsExecConfig) { |
| 4988 | // Bail out early if calling a builtin with custom typechecking. |
| 4989 | if (FDecl) |
| 4990 | if (unsigned ID = FDecl->getBuiltinID()) |
| 4991 | if (Context.BuiltinInfo.hasCustomTypechecking(ID)) |
| 4992 | return false; |
| 4993 | |
| 4994 | // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by |
| 4995 | // assignment, to the types of the corresponding parameter, ... |
| 4996 | unsigned NumParams = Proto->getNumParams(); |
| 4997 | bool Invalid = false; |
| 4998 | unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; |
| 4999 | unsigned FnKind = Fn->getType()->isBlockPointerType() |
| 5000 | ? 1 /* block */ |
| 5001 | : (IsExecConfig ? 3 /* kernel function (exec config) */ |
| 5002 | : 0 /* function */); |
| 5003 | |
| 5004 | // If too few arguments are available (and we don't have default |
| 5005 | // arguments for the remaining parameters), don't make the call. |
| 5006 | if (Args.size() < NumParams) { |
| 5007 | if (Args.size() < MinArgs) { |
| 5008 | TypoCorrection TC; |
| 5009 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { |
| 5010 | unsigned diag_id = |
| 5011 | MinArgs == NumParams && !Proto->isVariadic() |
| 5012 | ? diag::err_typecheck_call_too_few_args_suggest |
| 5013 | : diag::err_typecheck_call_too_few_args_at_least_suggest; |
| 5014 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs |
| 5015 | << static_cast<unsigned>(Args.size()) |
| 5016 | << TC.getCorrectionRange()); |
| 5017 | } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) |
| 5018 | Diag(RParenLoc, |
| 5019 | MinArgs == NumParams && !Proto->isVariadic() |
| 5020 | ? diag::err_typecheck_call_too_few_args_one |
| 5021 | : diag::err_typecheck_call_too_few_args_at_least_one) |
| 5022 | << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); |
| 5023 | else |
| 5024 | Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() |
| 5025 | ? diag::err_typecheck_call_too_few_args |
| 5026 | : diag::err_typecheck_call_too_few_args_at_least) |
| 5027 | << FnKind << MinArgs << static_cast<unsigned>(Args.size()) |
| 5028 | << Fn->getSourceRange(); |
| 5029 | |
| 5030 | // Emit the location of the prototype. |
| 5031 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
| 5032 | Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; |
| 5033 | |
| 5034 | return true; |
| 5035 | } |
| 5036 | // We reserve space for the default arguments when we create |
| 5037 | // the call expression, before calling ConvertArgumentsForCall. |
| 5038 | assert((Call->getNumArgs() == NumParams) && |
| 5039 | "We should have reserved space for the default arguments before!" ); |
| 5040 | } |
| 5041 | |
| 5042 | // If too many are passed and not variadic, error on the extras and drop |
| 5043 | // them. |
| 5044 | if (Args.size() > NumParams) { |
| 5045 | if (!Proto->isVariadic()) { |
| 5046 | TypoCorrection TC; |
| 5047 | if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { |
| 5048 | unsigned diag_id = |
| 5049 | MinArgs == NumParams && !Proto->isVariadic() |
| 5050 | ? diag::err_typecheck_call_too_many_args_suggest |
| 5051 | : diag::err_typecheck_call_too_many_args_at_most_suggest; |
| 5052 | diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams |
| 5053 | << static_cast<unsigned>(Args.size()) |
| 5054 | << TC.getCorrectionRange()); |
| 5055 | } else if (NumParams == 1 && FDecl && |
| 5056 | FDecl->getParamDecl(0)->getDeclName()) |
| 5057 | Diag(Args[NumParams]->getBeginLoc(), |
| 5058 | MinArgs == NumParams |
| 5059 | ? diag::err_typecheck_call_too_many_args_one |
| 5060 | : diag::err_typecheck_call_too_many_args_at_most_one) |
| 5061 | << FnKind << FDecl->getParamDecl(0) |
| 5062 | << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() |
| 5063 | << SourceRange(Args[NumParams]->getBeginLoc(), |
| 5064 | Args.back()->getEndLoc()); |
| 5065 | else |
| 5066 | Diag(Args[NumParams]->getBeginLoc(), |
| 5067 | MinArgs == NumParams |
| 5068 | ? diag::err_typecheck_call_too_many_args |
| 5069 | : diag::err_typecheck_call_too_many_args_at_most) |
| 5070 | << FnKind << NumParams << static_cast<unsigned>(Args.size()) |
| 5071 | << Fn->getSourceRange() |
| 5072 | << SourceRange(Args[NumParams]->getBeginLoc(), |
| 5073 | Args.back()->getEndLoc()); |
| 5074 | |
| 5075 | // Emit the location of the prototype. |
| 5076 | if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) |
| 5077 | Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; |
| 5078 | |
| 5079 | // This deletes the extra arguments. |
| 5080 | Call->shrinkNumArgs(NumParams); |
| 5081 | return true; |
| 5082 | } |
| 5083 | } |
| 5084 | SmallVector<Expr *, 8> AllArgs; |
| 5085 | VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); |
| 5086 | |
| 5087 | Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, |
| 5088 | AllArgs, CallType); |
| 5089 | if (Invalid) |
| 5090 | return true; |
| 5091 | unsigned TotalNumArgs = AllArgs.size(); |
| 5092 | for (unsigned i = 0; i < TotalNumArgs; ++i) |
| 5093 | Call->setArg(i, AllArgs[i]); |
| 5094 | |
| 5095 | return false; |
| 5096 | } |
| 5097 | |
| 5098 | bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, |
| 5099 | const FunctionProtoType *Proto, |
| 5100 | unsigned FirstParam, ArrayRef<Expr *> Args, |
| 5101 | SmallVectorImpl<Expr *> &AllArgs, |
| 5102 | VariadicCallType CallType, bool AllowExplicit, |
| 5103 | bool IsListInitialization) { |
| 5104 | unsigned NumParams = Proto->getNumParams(); |
| 5105 | bool Invalid = false; |
| 5106 | size_t ArgIx = 0; |
| 5107 | // Continue to check argument types (even if we have too few/many args). |
| 5108 | for (unsigned i = FirstParam; i < NumParams; i++) { |
| 5109 | QualType ProtoArgType = Proto->getParamType(i); |
| 5110 | |
| 5111 | Expr *Arg; |
| 5112 | ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; |
| 5113 | if (ArgIx < Args.size()) { |
| 5114 | Arg = Args[ArgIx++]; |
| 5115 | |
| 5116 | if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, |
| 5117 | diag::err_call_incomplete_argument, Arg)) |
| 5118 | return true; |
| 5119 | |
| 5120 | // Strip the unbridged-cast placeholder expression off, if applicable. |
| 5121 | bool CFAudited = false; |
| 5122 | if (Arg->getType() == Context.ARCUnbridgedCastTy && |
| 5123 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
| 5124 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
| 5125 | Arg = stripARCUnbridgedCast(Arg); |
| 5126 | else if (getLangOpts().ObjCAutoRefCount && |
| 5127 | FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && |
| 5128 | (!Param || !Param->hasAttr<CFConsumedAttr>())) |
| 5129 | CFAudited = true; |
| 5130 | |
| 5131 | if (Proto->getExtParameterInfo(i).isNoEscape()) |
| 5132 | if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) |
| 5133 | BE->getBlockDecl()->setDoesNotEscape(); |
| 5134 | |
| 5135 | InitializedEntity Entity = |
| 5136 | Param ? InitializedEntity::InitializeParameter(Context, Param, |
| 5137 | ProtoArgType) |
| 5138 | : InitializedEntity::InitializeParameter( |
| 5139 | Context, ProtoArgType, Proto->isParamConsumed(i)); |
| 5140 | |
| 5141 | // Remember that parameter belongs to a CF audited API. |
| 5142 | if (CFAudited) |
| 5143 | Entity.setParameterCFAudited(); |
| 5144 | |
| 5145 | ExprResult ArgE = PerformCopyInitialization( |
| 5146 | Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); |
| 5147 | if (ArgE.isInvalid()) |
| 5148 | return true; |
| 5149 | |
| 5150 | Arg = ArgE.getAs<Expr>(); |
| 5151 | } else { |
| 5152 | assert(Param && "can't use default arguments without a known callee" ); |
| 5153 | |
| 5154 | ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); |
| 5155 | if (ArgExpr.isInvalid()) |
| 5156 | return true; |
| 5157 | |
| 5158 | Arg = ArgExpr.getAs<Expr>(); |
| 5159 | } |
| 5160 | |
| 5161 | // Check for array bounds violations for each argument to the call. This |
| 5162 | // check only triggers warnings when the argument isn't a more complex Expr |
| 5163 | // with its own checking, such as a BinaryOperator. |
| 5164 | CheckArrayAccess(Arg); |
| 5165 | |
| 5166 | // Check for violations of C99 static array rules (C99 6.7.5.3p7). |
| 5167 | CheckStaticArrayArgument(CallLoc, Param, Arg); |
| 5168 | |
| 5169 | AllArgs.push_back(Arg); |
| 5170 | } |
| 5171 | |
| 5172 | // If this is a variadic call, handle args passed through "...". |
| 5173 | if (CallType != VariadicDoesNotApply) { |
| 5174 | // Assume that extern "C" functions with variadic arguments that |
| 5175 | // return __unknown_anytype aren't *really* variadic. |
| 5176 | if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && |
| 5177 | FDecl->isExternC()) { |
| 5178 | for (Expr *A : Args.slice(ArgIx)) { |
| 5179 | QualType paramType; // ignored |
| 5180 | ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); |
| 5181 | Invalid |= arg.isInvalid(); |
| 5182 | AllArgs.push_back(arg.get()); |
| 5183 | } |
| 5184 | |
| 5185 | // Otherwise do argument promotion, (C99 6.5.2.2p7). |
| 5186 | } else { |
| 5187 | for (Expr *A : Args.slice(ArgIx)) { |
| 5188 | ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); |
| 5189 | Invalid |= Arg.isInvalid(); |
| 5190 | AllArgs.push_back(Arg.get()); |
| 5191 | } |
| 5192 | } |
| 5193 | |
| 5194 | // Check for array bounds violations. |
| 5195 | for (Expr *A : Args.slice(ArgIx)) |
| 5196 | CheckArrayAccess(A); |
| 5197 | } |
| 5198 | return Invalid; |
| 5199 | } |
| 5200 | |
| 5201 | static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { |
| 5202 | TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); |
| 5203 | if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) |
| 5204 | TL = DTL.getOriginalLoc(); |
| 5205 | if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) |
| 5206 | S.Diag(PVD->getLocation(), diag::note_callee_static_array) |
| 5207 | << ATL.getLocalSourceRange(); |
| 5208 | } |
| 5209 | |
| 5210 | /// CheckStaticArrayArgument - If the given argument corresponds to a static |
| 5211 | /// array parameter, check that it is non-null, and that if it is formed by |
| 5212 | /// array-to-pointer decay, the underlying array is sufficiently large. |
| 5213 | /// |
| 5214 | /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the |
| 5215 | /// array type derivation, then for each call to the function, the value of the |
| 5216 | /// corresponding actual argument shall provide access to the first element of |
| 5217 | /// an array with at least as many elements as specified by the size expression. |
| 5218 | void |
| 5219 | Sema::CheckStaticArrayArgument(SourceLocation CallLoc, |
| 5220 | ParmVarDecl *Param, |
| 5221 | const Expr *ArgExpr) { |
| 5222 | // Static array parameters are not supported in C++. |
| 5223 | if (!Param || getLangOpts().CPlusPlus) |
| 5224 | return; |
| 5225 | |
| 5226 | QualType OrigTy = Param->getOriginalType(); |
| 5227 | |
| 5228 | const ArrayType *AT = Context.getAsArrayType(OrigTy); |
| 5229 | if (!AT || AT->getSizeModifier() != ArrayType::Static) |
| 5230 | return; |
| 5231 | |
| 5232 | if (ArgExpr->isNullPointerConstant(Context, |
| 5233 | Expr::NPC_NeverValueDependent)) { |
| 5234 | Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); |
| 5235 | DiagnoseCalleeStaticArrayParam(*this, Param); |
| 5236 | return; |
| 5237 | } |
| 5238 | |
| 5239 | const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); |
| 5240 | if (!CAT) |
| 5241 | return; |
| 5242 | |
| 5243 | const ConstantArrayType *ArgCAT = |
| 5244 | Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); |
| 5245 | if (!ArgCAT) |
| 5246 | return; |
| 5247 | |
| 5248 | if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), |
| 5249 | ArgCAT->getElementType())) { |
| 5250 | if (ArgCAT->getSize().ult(CAT->getSize())) { |
| 5251 | Diag(CallLoc, diag::warn_static_array_too_small) |
| 5252 | << ArgExpr->getSourceRange() |
| 5253 | << (unsigned)ArgCAT->getSize().getZExtValue() |
| 5254 | << (unsigned)CAT->getSize().getZExtValue() << 0; |
| 5255 | DiagnoseCalleeStaticArrayParam(*this, Param); |
| 5256 | } |
| 5257 | return; |
| 5258 | } |
| 5259 | |
| 5260 | Optional<CharUnits> ArgSize = |
| 5261 | getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); |
| 5262 | Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); |
| 5263 | if (ArgSize && ParmSize && *ArgSize < *ParmSize) { |
| 5264 | Diag(CallLoc, diag::warn_static_array_too_small) |
| 5265 | << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() |
| 5266 | << (unsigned)ParmSize->getQuantity() << 1; |
| 5267 | DiagnoseCalleeStaticArrayParam(*this, Param); |
| 5268 | } |
| 5269 | } |
| 5270 | |
| 5271 | /// Given a function expression of unknown-any type, try to rebuild it |
| 5272 | /// to have a function type. |
| 5273 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); |
| 5274 | |
| 5275 | /// Is the given type a placeholder that we need to lower out |
| 5276 | /// immediately during argument processing? |
| 5277 | static bool isPlaceholderToRemoveAsArg(QualType type) { |
| 5278 | // Placeholders are never sugared. |
| 5279 | const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); |
| 5280 | if (!placeholder) return false; |
| 5281 | |
| 5282 | switch (placeholder->getKind()) { |
| 5283 | // Ignore all the non-placeholder types. |
| 5284 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
| 5285 | case BuiltinType::Id: |
| 5286 | #include "clang/Basic/OpenCLImageTypes.def" |
| 5287 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 5288 | case BuiltinType::Id: |
| 5289 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 5290 | #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) |
| 5291 | #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: |
| 5292 | #include "clang/AST/BuiltinTypes.def" |
| 5293 | return false; |
| 5294 | |
| 5295 | // We cannot lower out overload sets; they might validly be resolved |
| 5296 | // by the call machinery. |
| 5297 | case BuiltinType::Overload: |
| 5298 | return false; |
| 5299 | |
| 5300 | // Unbridged casts in ARC can be handled in some call positions and |
| 5301 | // should be left in place. |
| 5302 | case BuiltinType::ARCUnbridgedCast: |
| 5303 | return false; |
| 5304 | |
| 5305 | // Pseudo-objects should be converted as soon as possible. |
| 5306 | case BuiltinType::PseudoObject: |
| 5307 | return true; |
| 5308 | |
| 5309 | // The debugger mode could theoretically but currently does not try |
| 5310 | // to resolve unknown-typed arguments based on known parameter types. |
| 5311 | case BuiltinType::UnknownAny: |
| 5312 | return true; |
| 5313 | |
| 5314 | // These are always invalid as call arguments and should be reported. |
| 5315 | case BuiltinType::BoundMember: |
| 5316 | case BuiltinType::BuiltinFn: |
| 5317 | case BuiltinType::OMPArraySection: |
| 5318 | return true; |
| 5319 | |
| 5320 | } |
| 5321 | llvm_unreachable("bad builtin type kind" ); |
| 5322 | } |
| 5323 | |
| 5324 | /// Check an argument list for placeholders that we won't try to |
| 5325 | /// handle later. |
| 5326 | static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { |
| 5327 | // Apply this processing to all the arguments at once instead of |
| 5328 | // dying at the first failure. |
| 5329 | bool hasInvalid = false; |
| 5330 | for (size_t i = 0, e = args.size(); i != e; i++) { |
| 5331 | if (isPlaceholderToRemoveAsArg(args[i]->getType())) { |
| 5332 | ExprResult result = S.CheckPlaceholderExpr(args[i]); |
| 5333 | if (result.isInvalid()) hasInvalid = true; |
| 5334 | else args[i] = result.get(); |
| 5335 | } else if (hasInvalid) { |
| 5336 | (void)S.CorrectDelayedTyposInExpr(args[i]); |
| 5337 | } |
| 5338 | } |
| 5339 | return hasInvalid; |
| 5340 | } |
| 5341 | |
| 5342 | /// If a builtin function has a pointer argument with no explicit address |
| 5343 | /// space, then it should be able to accept a pointer to any address |
| 5344 | /// space as input. In order to do this, we need to replace the |
| 5345 | /// standard builtin declaration with one that uses the same address space |
| 5346 | /// as the call. |
| 5347 | /// |
| 5348 | /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. |
| 5349 | /// it does not contain any pointer arguments without |
| 5350 | /// an address space qualifer. Otherwise the rewritten |
| 5351 | /// FunctionDecl is returned. |
| 5352 | /// TODO: Handle pointer return types. |
| 5353 | static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, |
| 5354 | const FunctionDecl *FDecl, |
| 5355 | MultiExprArg ArgExprs) { |
| 5356 | |
| 5357 | QualType DeclType = FDecl->getType(); |
| 5358 | const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); |
| 5359 | |
| 5360 | if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || |
| 5361 | !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) |
| 5362 | return nullptr; |
| 5363 | |
| 5364 | bool NeedsNewDecl = false; |
| 5365 | unsigned i = 0; |
| 5366 | SmallVector<QualType, 8> OverloadParams; |
| 5367 | |
| 5368 | for (QualType ParamType : FT->param_types()) { |
| 5369 | |
| 5370 | // Convert array arguments to pointer to simplify type lookup. |
| 5371 | ExprResult ArgRes = |
| 5372 | Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); |
| 5373 | if (ArgRes.isInvalid()) |
| 5374 | return nullptr; |
| 5375 | Expr *Arg = ArgRes.get(); |
| 5376 | QualType ArgType = Arg->getType(); |
| 5377 | if (!ParamType->isPointerType() || |
| 5378 | ParamType.getQualifiers().hasAddressSpace() || |
| 5379 | !ArgType->isPointerType() || |
| 5380 | !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { |
| 5381 | OverloadParams.push_back(ParamType); |
| 5382 | continue; |
| 5383 | } |
| 5384 | |
| 5385 | QualType PointeeType = ParamType->getPointeeType(); |
| 5386 | if (PointeeType.getQualifiers().hasAddressSpace()) |
| 5387 | continue; |
| 5388 | |
| 5389 | NeedsNewDecl = true; |
| 5390 | LangAS AS = ArgType->getPointeeType().getAddressSpace(); |
| 5391 | |
| 5392 | PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); |
| 5393 | OverloadParams.push_back(Context.getPointerType(PointeeType)); |
| 5394 | } |
| 5395 | |
| 5396 | if (!NeedsNewDecl) |
| 5397 | return nullptr; |
| 5398 | |
| 5399 | FunctionProtoType::ExtProtoInfo EPI; |
| 5400 | QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), |
| 5401 | OverloadParams, EPI); |
| 5402 | DeclContext *Parent = Context.getTranslationUnitDecl(); |
| 5403 | FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, |
| 5404 | FDecl->getLocation(), |
| 5405 | FDecl->getLocation(), |
| 5406 | FDecl->getIdentifier(), |
| 5407 | OverloadTy, |
| 5408 | /*TInfo=*/nullptr, |
| 5409 | SC_Extern, false, |
| 5410 | /*hasPrototype=*/true); |
| 5411 | SmallVector<ParmVarDecl*, 16> Params; |
| 5412 | FT = cast<FunctionProtoType>(OverloadTy); |
| 5413 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
| 5414 | QualType ParamType = FT->getParamType(i); |
| 5415 | ParmVarDecl *Parm = |
| 5416 | ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), |
| 5417 | SourceLocation(), nullptr, ParamType, |
| 5418 | /*TInfo=*/nullptr, SC_None, nullptr); |
| 5419 | Parm->setScopeInfo(0, i); |
| 5420 | Params.push_back(Parm); |
| 5421 | } |
| 5422 | OverloadDecl->setParams(Params); |
| 5423 | return OverloadDecl; |
| 5424 | } |
| 5425 | |
| 5426 | static void checkDirectCallValidity(Sema &S, const Expr *Fn, |
| 5427 | FunctionDecl *Callee, |
| 5428 | MultiExprArg ArgExprs) { |
| 5429 | |
| 5430 | // For purecap CHERI, output a warning if the callee doesn't have a prototype |
| 5431 | // and we are passing arguments. This would normally lead to using the |
| 5432 | // variadic calling convention. In the case of MIPS CHERI, this could lead to |
| 5433 | // runtime stack corruption if the callee function is not actually variadic. |
| 5434 | if (S.Context.getTargetInfo().SupportsCapabilities()) { |
| 5435 | bool NoProto = !Callee->getBuiltinID() && Callee->getType()->isFunctionNoProtoType(); |
| 5436 | if (NoProto && ArgExprs.size() > 0) { |
| 5437 | S.Diag(Fn->getBeginLoc(), diag::warn_mips_cheri_call_no_func_proto) |
| 5438 | << Callee->getName() << Fn->getSourceRange(); |
| 5439 | S.Diag(Callee->getLocation(), diag::note_mips_cheri_func_decl_add_types); |
| 5440 | S.Diag(Fn->getBeginLoc(), diag::note_mips_cheri_func_noproto_explanation); |
| 5441 | return; |
| 5442 | } |
| 5443 | } |
| 5444 | |
| 5445 | // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and |
| 5446 | // similar attributes) really don't like it when functions are called with an |
| 5447 | // invalid number of args. |
| 5448 | if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), |
| 5449 | /*PartialOverloading=*/false) && |
| 5450 | !Callee->isVariadic()) |
| 5451 | return; |
| 5452 | if (Callee->getMinRequiredArguments() > ArgExprs.size()) |
| 5453 | return; |
| 5454 | |
| 5455 | if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { |
| 5456 | S.Diag(Fn->getBeginLoc(), |
| 5457 | isa<CXXMethodDecl>(Callee) |
| 5458 | ? diag::err_ovl_no_viable_member_function_in_call |
| 5459 | : diag::err_ovl_no_viable_function_in_call) |
| 5460 | << Callee << Callee->getSourceRange(); |
| 5461 | S.Diag(Callee->getLocation(), |
| 5462 | diag::note_ovl_candidate_disabled_by_function_cond_attr) |
| 5463 | << Attr->getCond()->getSourceRange() << Attr->getMessage(); |
| 5464 | return; |
| 5465 | } |
| 5466 | } |
| 5467 | |
| 5468 | static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( |
| 5469 | const UnresolvedMemberExpr *const UME, Sema &S) { |
| 5470 | |
| 5471 | const auto GetFunctionLevelDCIfCXXClass = |
| 5472 | [](Sema &S) -> const CXXRecordDecl * { |
| 5473 | const DeclContext *const DC = S.getFunctionLevelDeclContext(); |
| 5474 | if (!DC || !DC->getParent()) |
| 5475 | return nullptr; |
| 5476 | |
| 5477 | // If the call to some member function was made from within a member |
| 5478 | // function body 'M' return return 'M's parent. |
| 5479 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) |
| 5480 | return MD->getParent()->getCanonicalDecl(); |
| 5481 | // else the call was made from within a default member initializer of a |
| 5482 | // class, so return the class. |
| 5483 | if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) |
| 5484 | return RD->getCanonicalDecl(); |
| 5485 | return nullptr; |
| 5486 | }; |
| 5487 | // If our DeclContext is neither a member function nor a class (in the |
| 5488 | // case of a lambda in a default member initializer), we can't have an |
| 5489 | // enclosing 'this'. |
| 5490 | |
| 5491 | const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); |
| 5492 | if (!CurParentClass) |
| 5493 | return false; |
| 5494 | |
| 5495 | // The naming class for implicit member functions call is the class in which |
| 5496 | // name lookup starts. |
| 5497 | const CXXRecordDecl *const NamingClass = |
| 5498 | UME->getNamingClass()->getCanonicalDecl(); |
| 5499 | assert(NamingClass && "Must have naming class even for implicit access" ); |
| 5500 | |
| 5501 | // If the unresolved member functions were found in a 'naming class' that is |
| 5502 | // related (either the same or derived from) to the class that contains the |
| 5503 | // member function that itself contained the implicit member access. |
| 5504 | |
| 5505 | return CurParentClass == NamingClass || |
| 5506 | CurParentClass->isDerivedFrom(NamingClass); |
| 5507 | } |
| 5508 | |
| 5509 | static void |
| 5510 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
| 5511 | Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { |
| 5512 | |
| 5513 | if (!UME) |
| 5514 | return; |
| 5515 | |
| 5516 | LambdaScopeInfo *const CurLSI = S.getCurLambda(); |
| 5517 | // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't |
| 5518 | // already been captured, or if this is an implicit member function call (if |
| 5519 | // it isn't, an attempt to capture 'this' should already have been made). |
| 5520 | if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || |
| 5521 | !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) |
| 5522 | return; |
| 5523 | |
| 5524 | // Check if the naming class in which the unresolved members were found is |
| 5525 | // related (same as or is a base of) to the enclosing class. |
| 5526 | |
| 5527 | if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) |
| 5528 | return; |
| 5529 | |
| 5530 | |
| 5531 | DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); |
| 5532 | // If the enclosing function is not dependent, then this lambda is |
| 5533 | // capture ready, so if we can capture this, do so. |
| 5534 | if (!EnclosingFunctionCtx->isDependentContext()) { |
| 5535 | // If the current lambda and all enclosing lambdas can capture 'this' - |
| 5536 | // then go ahead and capture 'this' (since our unresolved overload set |
| 5537 | // contains at least one non-static member function). |
| 5538 | if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) |
| 5539 | S.CheckCXXThisCapture(CallLoc); |
| 5540 | } else if (S.CurContext->isDependentContext()) { |
| 5541 | // ... since this is an implicit member reference, that might potentially |
| 5542 | // involve a 'this' capture, mark 'this' for potential capture in |
| 5543 | // enclosing lambdas. |
| 5544 | if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) |
| 5545 | CurLSI->addPotentialThisCapture(CallLoc); |
| 5546 | } |
| 5547 | } |
| 5548 | |
| 5549 | ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
| 5550 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
| 5551 | Expr *ExecConfig) { |
| 5552 | ExprResult Call = |
| 5553 | BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); |
| 5554 | if (Call.isInvalid()) |
| 5555 | return Call; |
| 5556 | |
| 5557 | // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier |
| 5558 | // language modes. |
| 5559 | if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { |
| 5560 | if (ULE->hasExplicitTemplateArgs() && |
| 5561 | ULE->decls_begin() == ULE->decls_end()) { |
| 5562 | Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a |
| 5563 | ? diag::warn_cxx17_compat_adl_only_template_id |
| 5564 | : diag::ext_adl_only_template_id) |
| 5565 | << ULE->getName(); |
| 5566 | } |
| 5567 | } |
| 5568 | |
| 5569 | return Call; |
| 5570 | } |
| 5571 | |
| 5572 | /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. |
| 5573 | /// This provides the location of the left/right parens and a list of comma |
| 5574 | /// locations. |
| 5575 | ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, |
| 5576 | MultiExprArg ArgExprs, SourceLocation RParenLoc, |
| 5577 | Expr *ExecConfig, bool IsExecConfig) { |
| 5578 | // Since this might be a postfix expression, get rid of ParenListExprs. |
| 5579 | ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); |
| 5580 | if (Result.isInvalid()) return ExprError(); |
| 5581 | Fn = Result.get(); |
| 5582 | |
| 5583 | if (checkArgsForPlaceholders(*this, ArgExprs)) |
| 5584 | return ExprError(); |
| 5585 | |
| 5586 | if (getLangOpts().CPlusPlus) { |
| 5587 | // If this is a pseudo-destructor expression, build the call immediately. |
| 5588 | if (isa<CXXPseudoDestructorExpr>(Fn)) { |
| 5589 | if (!ArgExprs.empty()) { |
| 5590 | // Pseudo-destructor calls should not have any arguments. |
| 5591 | Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) |
| 5592 | << FixItHint::CreateRemoval( |
| 5593 | SourceRange(ArgExprs.front()->getBeginLoc(), |
| 5594 | ArgExprs.back()->getEndLoc())); |
| 5595 | } |
| 5596 | |
| 5597 | return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, |
| 5598 | VK_RValue, RParenLoc); |
| 5599 | } |
| 5600 | if (Fn->getType() == Context.PseudoObjectTy) { |
| 5601 | ExprResult result = CheckPlaceholderExpr(Fn); |
| 5602 | if (result.isInvalid()) return ExprError(); |
| 5603 | Fn = result.get(); |
| 5604 | } |
| 5605 | |
| 5606 | // Determine whether this is a dependent call inside a C++ template, |
| 5607 | // in which case we won't do any semantic analysis now. |
| 5608 | if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { |
| 5609 | if (ExecConfig) { |
| 5610 | return CUDAKernelCallExpr::Create( |
| 5611 | Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, |
| 5612 | Context.DependentTy, VK_RValue, RParenLoc); |
| 5613 | } else { |
| 5614 | |
| 5615 | tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( |
| 5616 | *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), |
| 5617 | Fn->getBeginLoc()); |
| 5618 | |
| 5619 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, |
| 5620 | VK_RValue, RParenLoc); |
| 5621 | } |
| 5622 | } |
| 5623 | |
| 5624 | // Determine whether this is a call to an object (C++ [over.call.object]). |
| 5625 | if (Fn->getType()->isRecordType()) |
| 5626 | return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, |
| 5627 | RParenLoc); |
| 5628 | |
| 5629 | if (Fn->getType() == Context.UnknownAnyTy) { |
| 5630 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); |
| 5631 | if (result.isInvalid()) return ExprError(); |
| 5632 | Fn = result.get(); |
| 5633 | } |
| 5634 | |
| 5635 | if (Fn->getType() == Context.BoundMemberTy) { |
| 5636 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, |
| 5637 | RParenLoc); |
| 5638 | } |
| 5639 | } |
| 5640 | |
| 5641 | // Check for overloaded calls. This can happen even in C due to extensions. |
| 5642 | if (Fn->getType() == Context.OverloadTy) { |
| 5643 | OverloadExpr::FindResult find = OverloadExpr::find(Fn); |
| 5644 | |
| 5645 | // We aren't supposed to apply this logic if there's an '&' involved. |
| 5646 | if (!find.HasFormOfMemberPointer) { |
| 5647 | if (Expr::hasAnyTypeDependentArguments(ArgExprs)) |
| 5648 | return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, |
| 5649 | VK_RValue, RParenLoc); |
| 5650 | OverloadExpr *ovl = find.Expression; |
| 5651 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) |
| 5652 | return BuildOverloadedCallExpr( |
| 5653 | Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, |
| 5654 | /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); |
| 5655 | return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, |
| 5656 | RParenLoc); |
| 5657 | } |
| 5658 | } |
| 5659 | |
| 5660 | // If we're directly calling a function, get the appropriate declaration. |
| 5661 | if (Fn->getType() == Context.UnknownAnyTy) { |
| 5662 | ExprResult result = rebuildUnknownAnyFunction(*this, Fn); |
| 5663 | if (result.isInvalid()) return ExprError(); |
| 5664 | Fn = result.get(); |
| 5665 | } |
| 5666 | |
| 5667 | Expr *NakedFn = Fn->IgnoreParens(); |
| 5668 | |
| 5669 | bool CallingNDeclIndirectly = false; |
| 5670 | NamedDecl *NDecl = nullptr; |
| 5671 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { |
| 5672 | if (UnOp->getOpcode() == UO_AddrOf) { |
| 5673 | CallingNDeclIndirectly = true; |
| 5674 | NakedFn = UnOp->getSubExpr()->IgnoreParens(); |
| 5675 | } |
| 5676 | } |
| 5677 | |
| 5678 | if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { |
| 5679 | NDecl = DRE->getDecl(); |
| 5680 | |
| 5681 | FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); |
| 5682 | if (FDecl && FDecl->getBuiltinID()) { |
| 5683 | // Rewrite the function decl for this builtin by replacing parameters |
| 5684 | // with no explicit address space with the address space of the arguments |
| 5685 | // in ArgExprs. |
| 5686 | if ((FDecl = |
| 5687 | rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { |
| 5688 | NDecl = FDecl; |
| 5689 | Fn = DeclRefExpr::Create( |
| 5690 | Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, |
| 5691 | SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, |
| 5692 | nullptr, DRE->isNonOdrUse()); |
| 5693 | } |
| 5694 | } |
| 5695 | } else if (isa<MemberExpr>(NakedFn)) |
| 5696 | NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); |
| 5697 | |
| 5698 | if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { |
| 5699 | if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( |
| 5700 | FD, /*Complain=*/true, Fn->getBeginLoc())) |
| 5701 | return ExprError(); |
| 5702 | |
| 5703 | if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) |
| 5704 | return ExprError(); |
| 5705 | |
| 5706 | checkDirectCallValidity(*this, Fn, FD, ArgExprs); |
| 5707 | } |
| 5708 | |
| 5709 | return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, |
| 5710 | ExecConfig, IsExecConfig); |
| 5711 | } |
| 5712 | |
| 5713 | /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. |
| 5714 | /// |
| 5715 | /// __builtin_astype( value, dst type ) |
| 5716 | /// |
| 5717 | ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, |
| 5718 | SourceLocation BuiltinLoc, |
| 5719 | SourceLocation RParenLoc) { |
| 5720 | ExprValueKind VK = VK_RValue; |
| 5721 | ExprObjectKind OK = OK_Ordinary; |
| 5722 | QualType DstTy = GetTypeFromParser(ParsedDestTy); |
| 5723 | QualType SrcTy = E->getType(); |
| 5724 | if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) |
| 5725 | return ExprError(Diag(BuiltinLoc, |
| 5726 | diag::err_invalid_astype_of_different_size) |
| 5727 | << DstTy |
| 5728 | << SrcTy |
| 5729 | << E->getSourceRange()); |
| 5730 | return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); |
| 5731 | } |
| 5732 | |
| 5733 | /// ActOnConvertVectorExpr - create a new convert-vector expression from the |
| 5734 | /// provided arguments. |
| 5735 | /// |
| 5736 | /// __builtin_convertvector( value, dst type ) |
| 5737 | /// |
| 5738 | ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, |
| 5739 | SourceLocation BuiltinLoc, |
| 5740 | SourceLocation RParenLoc) { |
| 5741 | TypeSourceInfo *TInfo; |
| 5742 | GetTypeFromParser(ParsedDestTy, &TInfo); |
| 5743 | return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); |
| 5744 | } |
| 5745 | |
| 5746 | /// BuildResolvedCallExpr - Build a call to a resolved expression, |
| 5747 | /// i.e. an expression not of \p OverloadTy. The expression should |
| 5748 | /// unary-convert to an expression of function-pointer or |
| 5749 | /// block-pointer type. |
| 5750 | /// |
| 5751 | /// \param NDecl the declaration being called, if available |
| 5752 | ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, |
| 5753 | SourceLocation LParenLoc, |
| 5754 | ArrayRef<Expr *> Args, |
| 5755 | SourceLocation RParenLoc, Expr *Config, |
| 5756 | bool IsExecConfig, ADLCallKind UsesADL) { |
| 5757 | FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); |
| 5758 | unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); |
| 5759 | |
| 5760 | if (!BuiltinID) |
| 5761 | if (NamedDecl *currentDecl = getCurFunctionOrMethodDecl()) |
| 5762 | if (currentDecl->hasAttr<SensitiveAttr>() && |
| 5763 | (!FDecl || !FDecl->hasAttr<SensitiveAttr>())) |
| 5764 | Diag(RParenLoc, diag::warn_calling_non_sensitive_from_sensitive) |
| 5765 | << FDecl << currentDecl; |
| 5766 | |
| 5767 | |
| 5768 | // Functions with 'interrupt' attribute cannot be called directly. |
| 5769 | if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { |
| 5770 | Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); |
| 5771 | return ExprError(); |
| 5772 | } |
| 5773 | |
| 5774 | // Interrupt handlers don't save off the VFP regs automatically on ARM, |
| 5775 | // so there's some risk when calling out to non-interrupt handler functions |
| 5776 | // that the callee might not preserve them. This is easy to diagnose here, |
| 5777 | // but can be very challenging to debug. |
| 5778 | if (auto *Caller = getCurFunctionDecl()) |
| 5779 | if (Caller->hasAttr<ARMInterruptAttr>()) { |
| 5780 | bool VFP = Context.getTargetInfo().hasFeature("vfp" ); |
| 5781 | if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) |
| 5782 | Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); |
| 5783 | } |
| 5784 | |
| 5785 | // Promote the function operand. |
| 5786 | // We special-case function promotion here because we only allow promoting |
| 5787 | // builtin functions to function pointers in the callee of a call. |
| 5788 | ExprResult Result; |
| 5789 | QualType ResultTy; |
| 5790 | if (BuiltinID && |
| 5791 | Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { |
| 5792 | // Extract the return type from the (builtin) function pointer type. |
| 5793 | // FIXME Several builtins still have setType in |
| 5794 | // Sema::CheckBuiltinFunctionCall. One should review their definitions in |
| 5795 | // Builtins.def to ensure they are correct before removing setType calls. |
| 5796 | QualType FnPtrTy = Context.getPointerType(FDecl->getType()); |
| 5797 | Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); |
| 5798 | ResultTy = FDecl->getCallResultType(); |
| 5799 | } else { |
| 5800 | Result = CallExprUnaryConversions(Fn); |
| 5801 | ResultTy = Context.BoolTy; |
| 5802 | } |
| 5803 | if (Result.isInvalid()) |
| 5804 | return ExprError(); |
| 5805 | Fn = Result.get(); |
| 5806 | |
| 5807 | // Check for a valid function type, but only if it is not a builtin which |
| 5808 | // requires custom type checking. These will be handled by |
| 5809 | // CheckBuiltinFunctionCall below just after creation of the call expression. |
| 5810 | const FunctionType *FuncT = nullptr; |
| 5811 | if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { |
| 5812 | retry: |
| 5813 | if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { |
| 5814 | // C99 6.5.2.2p1 - "The expression that denotes the called function shall |
| 5815 | // have type pointer to function". |
| 5816 | FuncT = PT->getPointeeType()->getAs<FunctionType>(); |
| 5817 | if (!FuncT) |
| 5818 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) |
| 5819 | << Fn->getType() << Fn->getSourceRange()); |
| 5820 | } else if (const BlockPointerType *BPT = |
| 5821 | Fn->getType()->getAs<BlockPointerType>()) { |
| 5822 | FuncT = BPT->getPointeeType()->castAs<FunctionType>(); |
| 5823 | } else { |
| 5824 | // Handle calls to expressions of unknown-any type. |
| 5825 | if (Fn->getType() == Context.UnknownAnyTy) { |
| 5826 | ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); |
| 5827 | if (rewrite.isInvalid()) return ExprError(); |
| 5828 | Fn = rewrite.get(); |
| 5829 | goto retry; |
| 5830 | } |
| 5831 | |
| 5832 | return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) |
| 5833 | << Fn->getType() << Fn->getSourceRange()); |
| 5834 | } |
| 5835 | } |
| 5836 | |
| 5837 | // Get the number of parameters in the function prototype, if any. |
| 5838 | // We will allocate space for max(Args.size(), NumParams) arguments |
| 5839 | // in the call expression. |
| 5840 | const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); |
| 5841 | unsigned NumParams = Proto ? Proto->getNumParams() : 0; |
| 5842 | |
| 5843 | CallExpr *TheCall; |
| 5844 | if (Config) { |
| 5845 | assert(UsesADL == ADLCallKind::NotADL && |
| 5846 | "CUDAKernelCallExpr should not use ADL" ); |
| 5847 | TheCall = |
| 5848 | CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, |
| 5849 | ResultTy, VK_RValue, RParenLoc, NumParams); |
| 5850 | } else { |
| 5851 | TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, |
| 5852 | RParenLoc, NumParams, UsesADL); |
| 5853 | } |
| 5854 | |
| 5855 | if (!getLangOpts().CPlusPlus) { |
| 5856 | // Forget about the nulled arguments since typo correction |
| 5857 | // do not handle them well. |
| 5858 | TheCall->shrinkNumArgs(Args.size()); |
| 5859 | // C cannot always handle TypoExpr nodes in builtin calls and direct |
| 5860 | // function calls as their argument checking don't necessarily handle |
| 5861 | // dependent types properly, so make sure any TypoExprs have been |
| 5862 | // dealt with. |
| 5863 | ExprResult Result = CorrectDelayedTyposInExpr(TheCall); |
| 5864 | if (!Result.isUsable()) return ExprError(); |
| 5865 | CallExpr *TheOldCall = TheCall; |
| 5866 | TheCall = dyn_cast<CallExpr>(Result.get()); |
| 5867 | bool CorrectedTypos = TheCall != TheOldCall; |
| 5868 | if (!TheCall) return Result; |
| 5869 | Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); |
| 5870 | |
| 5871 | // A new call expression node was created if some typos were corrected. |
| 5872 | // However it may not have been constructed with enough storage. In this |
| 5873 | // case, rebuild the node with enough storage. The waste of space is |
| 5874 | // immaterial since this only happens when some typos were corrected. |
| 5875 | if (CorrectedTypos && Args.size() < NumParams) { |
| 5876 | if (Config) |
| 5877 | TheCall = CUDAKernelCallExpr::Create( |
| 5878 | Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, |
| 5879 | RParenLoc, NumParams); |
| 5880 | else |
| 5881 | TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, |
| 5882 | RParenLoc, NumParams, UsesADL); |
| 5883 | } |
| 5884 | // We can now handle the nulled arguments for the default arguments. |
| 5885 | TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); |
| 5886 | } |
| 5887 | |
| 5888 | // Bail out early if calling a builtin with custom type checking. |
| 5889 | if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) |
| 5890 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
| 5891 | |
| 5892 | if (getLangOpts().CUDA) { |
| 5893 | if (Config) { |
| 5894 | // CUDA: Kernel calls must be to global functions |
| 5895 | if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) |
| 5896 | return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) |
| 5897 | << FDecl << Fn->getSourceRange()); |
| 5898 | |
| 5899 | // CUDA: Kernel function must have 'void' return type |
| 5900 | if (!FuncT->getReturnType()->isVoidType()) |
| 5901 | return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) |
| 5902 | << Fn->getType() << Fn->getSourceRange()); |
| 5903 | } else { |
| 5904 | // CUDA: Calls to global functions must be configured |
| 5905 | if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) |
| 5906 | return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) |
| 5907 | << FDecl << Fn->getSourceRange()); |
| 5908 | } |
| 5909 | } |
| 5910 | |
| 5911 | // Check for a valid return type |
| 5912 | if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, |
| 5913 | FDecl)) |
| 5914 | return ExprError(); |
| 5915 | |
| 5916 | // We know the result type of the call, set it. |
| 5917 | TheCall->setType(FuncT->getCallResultType(Context)); |
| 5918 | TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); |
| 5919 | |
| 5920 | if (Proto) { |
| 5921 | if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, |
| 5922 | IsExecConfig)) |
| 5923 | return ExprError(); |
| 5924 | } else { |
| 5925 | assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!" ); |
| 5926 | |
| 5927 | if (FDecl) { |
| 5928 | // Check if we have too few/too many template arguments, based |
| 5929 | // on our knowledge of the function definition. |
| 5930 | const FunctionDecl *Def = nullptr; |
| 5931 | if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { |
| 5932 | Proto = Def->getType()->getAs<FunctionProtoType>(); |
| 5933 | if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) |
| 5934 | Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) |
| 5935 | << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); |
| 5936 | } |
| 5937 | |
| 5938 | // If the function we're calling isn't a function prototype, but we have |
| 5939 | // a function prototype from a prior declaratiom, use that prototype. |
| 5940 | if (!FDecl->hasPrototype()) |
| 5941 | Proto = FDecl->getType()->getAs<FunctionProtoType>(); |
| 5942 | } |
| 5943 | |
| 5944 | // Promote the arguments (C99 6.5.2.2p6). |
| 5945 | for (unsigned i = 0, e = Args.size(); i != e; i++) { |
| 5946 | Expr *Arg = Args[i]; |
| 5947 | |
| 5948 | if (Proto && i < Proto->getNumParams()) { |
| 5949 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
| 5950 | Context, Proto->getParamType(i), Proto->isParamConsumed(i)); |
| 5951 | ExprResult ArgE = |
| 5952 | PerformCopyInitialization(Entity, SourceLocation(), Arg); |
| 5953 | if (ArgE.isInvalid()) |
| 5954 | return true; |
| 5955 | |
| 5956 | Arg = ArgE.getAs<Expr>(); |
| 5957 | |
| 5958 | } else { |
| 5959 | ExprResult ArgE = DefaultArgumentPromotion(Arg); |
| 5960 | |
| 5961 | if (ArgE.isInvalid()) |
| 5962 | return true; |
| 5963 | |
| 5964 | Arg = ArgE.getAs<Expr>(); |
| 5965 | } |
| 5966 | |
| 5967 | if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), |
| 5968 | diag::err_call_incomplete_argument, Arg)) |
| 5969 | return ExprError(); |
| 5970 | |
| 5971 | TheCall->setArg(i, Arg); |
| 5972 | } |
| 5973 | } |
| 5974 | |
| 5975 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) |
| 5976 | if (!Method->isStatic()) |
| 5977 | return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) |
| 5978 | << Fn->getSourceRange()); |
| 5979 | |
| 5980 | // Check for sentinels |
| 5981 | if (NDecl) |
| 5982 | DiagnoseSentinelCalls(NDecl, LParenLoc, Args); |
| 5983 | |
| 5984 | // Do special checking on direct calls to functions. |
| 5985 | if (FDecl) { |
| 5986 | if (CheckFunctionCall(FDecl, TheCall, Proto)) |
| 5987 | return ExprError(); |
| 5988 | |
| 5989 | checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); |
| 5990 | |
| 5991 | if (BuiltinID) |
| 5992 | return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); |
| 5993 | } else if (NDecl) { |
| 5994 | if (CheckPointerCall(NDecl, TheCall, Proto)) |
| 5995 | return ExprError(); |
| 5996 | } else { |
| 5997 | if (CheckOtherCall(TheCall, Proto)) |
| 5998 | return ExprError(); |
| 5999 | } |
| 6000 | |
| 6001 | return MaybeBindToTemporary(TheCall); |
| 6002 | } |
| 6003 | |
| 6004 | ExprResult |
| 6005 | Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, |
| 6006 | SourceLocation RParenLoc, Expr *InitExpr) { |
| 6007 | assert(Ty && "ActOnCompoundLiteral(): missing type" ); |
| 6008 | assert(InitExpr && "ActOnCompoundLiteral(): missing expression" ); |
| 6009 | |
| 6010 | TypeSourceInfo *TInfo; |
| 6011 | QualType literalType = GetTypeFromParser(Ty, &TInfo); |
| 6012 | if (!TInfo) |
| 6013 | TInfo = Context.getTrivialTypeSourceInfo(literalType); |
| 6014 | |
| 6015 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); |
| 6016 | } |
| 6017 | |
| 6018 | ExprResult |
| 6019 | Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, |
| 6020 | SourceLocation RParenLoc, Expr *LiteralExpr) { |
| 6021 | QualType literalType = TInfo->getType(); |
| 6022 | |
| 6023 | if (literalType->isArrayType()) { |
| 6024 | if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), |
| 6025 | diag::err_illegal_decl_array_incomplete_type, |
| 6026 | SourceRange(LParenLoc, |
| 6027 | LiteralExpr->getSourceRange().getEnd()))) |
| 6028 | return ExprError(); |
| 6029 | if (literalType->isVariableArrayType()) |
| 6030 | return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) |
| 6031 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); |
| 6032 | } else if (!literalType->isDependentType() && |
| 6033 | RequireCompleteType(LParenLoc, literalType, |
| 6034 | diag::err_typecheck_decl_incomplete_type, |
| 6035 | SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) |
| 6036 | return ExprError(); |
| 6037 | |
| 6038 | InitializedEntity Entity |
| 6039 | = InitializedEntity::InitializeCompoundLiteralInit(TInfo); |
| 6040 | InitializationKind Kind |
| 6041 | = InitializationKind::CreateCStyleCast(LParenLoc, |
| 6042 | SourceRange(LParenLoc, RParenLoc), |
| 6043 | /*InitList=*/true); |
| 6044 | InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); |
| 6045 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, |
| 6046 | &literalType); |
| 6047 | if (Result.isInvalid()) |
| 6048 | return ExprError(); |
| 6049 | LiteralExpr = Result.get(); |
| 6050 | |
| 6051 | bool isFileScope = !CurContext->isFunctionOrMethod(); |
| 6052 | |
| 6053 | // In C, compound literals are l-values for some reason. |
| 6054 | // For GCC compatibility, in C++, file-scope array compound literals with |
| 6055 | // constant initializers are also l-values, and compound literals are |
| 6056 | // otherwise prvalues. |
| 6057 | // |
| 6058 | // (GCC also treats C++ list-initialized file-scope array prvalues with |
| 6059 | // constant initializers as l-values, but that's non-conforming, so we don't |
| 6060 | // follow it there.) |
| 6061 | // |
| 6062 | // FIXME: It would be better to handle the lvalue cases as materializing and |
| 6063 | // lifetime-extending a temporary object, but our materialized temporaries |
| 6064 | // representation only supports lifetime extension from a variable, not "out |
| 6065 | // of thin air". |
| 6066 | // FIXME: For C++, we might want to instead lifetime-extend only if a pointer |
| 6067 | // is bound to the result of applying array-to-pointer decay to the compound |
| 6068 | // literal. |
| 6069 | // FIXME: GCC supports compound literals of reference type, which should |
| 6070 | // obviously have a value kind derived from the kind of reference involved. |
| 6071 | ExprValueKind VK = |
| 6072 | (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) |
| 6073 | ? VK_RValue |
| 6074 | : VK_LValue; |
| 6075 | |
| 6076 | if (isFileScope) |
| 6077 | if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) |
| 6078 | for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { |
| 6079 | Expr *Init = ILE->getInit(i); |
| 6080 | ILE->setInit(i, ConstantExpr::Create(Context, Init)); |
| 6081 | } |
| 6082 | |
| 6083 | Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, |
| 6084 | VK, LiteralExpr, isFileScope); |
| 6085 | if (isFileScope) { |
| 6086 | if (!LiteralExpr->isTypeDependent() && |
| 6087 | !LiteralExpr->isValueDependent() && |
| 6088 | !literalType->isDependentType()) // C99 6.5.2.5p3 |
| 6089 | if (CheckForConstantInitializer(LiteralExpr, literalType)) |
| 6090 | return ExprError(); |
| 6091 | } else if (literalType.getAddressSpace() != LangAS::opencl_private && |
| 6092 | literalType.getAddressSpace() != LangAS::Default) { |
| 6093 | // Embedded-C extensions to C99 6.5.2.5: |
| 6094 | // "If the compound literal occurs inside the body of a function, the |
| 6095 | // type name shall not be qualified by an address-space qualifier." |
| 6096 | Diag(LParenLoc, diag::err_compound_literal_with_address_space) |
| 6097 | << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); |
| 6098 | return ExprError(); |
| 6099 | } |
| 6100 | |
| 6101 | return MaybeBindToTemporary(E); |
| 6102 | } |
| 6103 | |
| 6104 | ExprResult |
| 6105 | Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, |
| 6106 | SourceLocation RBraceLoc) { |
| 6107 | // Immediately handle non-overload placeholders. Overloads can be |
| 6108 | // resolved contextually, but everything else here can't. |
| 6109 | for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { |
| 6110 | if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { |
| 6111 | ExprResult result = CheckPlaceholderExpr(InitArgList[I]); |
| 6112 | |
| 6113 | // Ignore failures; dropping the entire initializer list because |
| 6114 | // of one failure would be terrible for indexing/etc. |
| 6115 | if (result.isInvalid()) continue; |
| 6116 | |
| 6117 | InitArgList[I] = result.get(); |
| 6118 | } |
| 6119 | } |
| 6120 | |
| 6121 | // Semantic analysis for initializers is done by ActOnDeclarator() and |
| 6122 | // CheckInitializer() - it requires knowledge of the object being initialized. |
| 6123 | |
| 6124 | InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, |
| 6125 | RBraceLoc); |
| 6126 | E->setType(Context.VoidTy); // FIXME: just a place holder for now. |
| 6127 | return E; |
| 6128 | } |
| 6129 | |
| 6130 | /// Do an explicit extend of the given block pointer if we're in ARC. |
| 6131 | void Sema::maybeExtendBlockObject(ExprResult &E) { |
| 6132 | assert(E.get()->getType()->isBlockPointerType()); |
| 6133 | assert(E.get()->isRValue()); |
| 6134 | |
| 6135 | // Only do this in an r-value context. |
| 6136 | if (!getLangOpts().ObjCAutoRefCount) return; |
| 6137 | |
| 6138 | E = ImplicitCastExpr::Create(Context, E.get()->getType(), |
| 6139 | CK_ARCExtendBlockObject, E.get(), |
| 6140 | /*base path*/ nullptr, VK_RValue); |
| 6141 | Cleanup.setExprNeedsCleanups(true); |
| 6142 | } |
| 6143 | |
| 6144 | /// Prepare a conversion of the given expression to an ObjC object |
| 6145 | /// pointer type. |
| 6146 | CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { |
| 6147 | QualType type = E.get()->getType(); |
| 6148 | if (type->isObjCObjectPointerType()) { |
| 6149 | return CK_BitCast; |
| 6150 | } else if (type->isBlockPointerType()) { |
| 6151 | maybeExtendBlockObject(E); |
| 6152 | return CK_BlockPointerToObjCPointerCast; |
| 6153 | } else { |
| 6154 | assert(type->isPointerType()); |
| 6155 | return CK_CPointerToObjCPointerCast; |
| 6156 | } |
| 6157 | } |
| 6158 | |
| 6159 | /// Prepares for a scalar cast, performing all the necessary stages |
| 6160 | /// except the final cast and returning the kind required. |
| 6161 | CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { |
| 6162 | // Both Src and Dest are scalar types, i.e. arithmetic or pointer. |
| 6163 | // Also, callers should have filtered out the invalid cases with |
| 6164 | // pointers. Everything else should be possible. |
| 6165 | |
| 6166 | QualType SrcTy = Src.get()->getType(); |
| 6167 | if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) |
| 6168 | return CK_NoOp; |
| 6169 | |
| 6170 | switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { |
| 6171 | case Type::STK_MemberPointer: |
| 6172 | llvm_unreachable("member pointer type in C" ); |
| 6173 | |
| 6174 | case Type::STK_CPointer: |
| 6175 | case Type::STK_BlockPointer: |
| 6176 | case Type::STK_ObjCObjectPointer: |
| 6177 | switch (DestTy->getScalarTypeKind()) { |
| 6178 | case Type::STK_CPointer: { |
| 6179 | LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); |
| 6180 | LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); |
| 6181 | if (SrcAS != DestAS) |
| 6182 | return CK_AddressSpaceConversion; |
| 6183 | else if (!SrcTy->isCHERICapabilityType(Context) && DestTy->isCHERICapabilityType(Context)) |
| 6184 | return CK_PointerToCHERICapability; |
| 6185 | else if (SrcTy->isCHERICapabilityType(Context) && !DestTy->isCHERICapabilityType(Context)) |
| 6186 | return CK_CHERICapabilityToPointer; |
| 6187 | else if (Context.hasCvrSimilarType(SrcTy, DestTy)) |
| 6188 | return CK_NoOp; |
| 6189 | return CK_BitCast; |
| 6190 | } |
| 6191 | case Type::STK_BlockPointer: |
| 6192 | return (SrcKind == Type::STK_BlockPointer |
| 6193 | ? CK_BitCast : CK_AnyPointerToBlockPointerCast); |
| 6194 | case Type::STK_ObjCObjectPointer: |
| 6195 | if (SrcKind == Type::STK_ObjCObjectPointer) |
| 6196 | return CK_BitCast; |
| 6197 | if (SrcKind == Type::STK_CPointer) |
| 6198 | return CK_CPointerToObjCPointerCast; |
| 6199 | maybeExtendBlockObject(Src); |
| 6200 | return CK_BlockPointerToObjCPointerCast; |
| 6201 | case Type::STK_Bool: |
| 6202 | return CK_PointerToBoolean; |
| 6203 | case Type::STK_Integral: |
| 6204 | return CK_PointerToIntegral; |
| 6205 | case Type::STK_Floating: |
| 6206 | case Type::STK_FloatingComplex: |
| 6207 | case Type::STK_IntegralComplex: |
| 6208 | case Type::STK_MemberPointer: |
| 6209 | case Type::STK_FixedPoint: |
| 6210 | llvm_unreachable("illegal cast from pointer" ); |
| 6211 | } |
| 6212 | llvm_unreachable("Should have returned before this" ); |
| 6213 | |
| 6214 | case Type::STK_FixedPoint: |
| 6215 | switch (DestTy->getScalarTypeKind()) { |
| 6216 | case Type::STK_FixedPoint: |
| 6217 | return CK_FixedPointCast; |
| 6218 | case Type::STK_Bool: |
| 6219 | return CK_FixedPointToBoolean; |
| 6220 | case Type::STK_Integral: |
| 6221 | return CK_FixedPointToIntegral; |
| 6222 | case Type::STK_Floating: |
| 6223 | case Type::STK_IntegralComplex: |
| 6224 | case Type::STK_FloatingComplex: |
| 6225 | Diag(Src.get()->getExprLoc(), |
| 6226 | diag::err_unimplemented_conversion_with_fixed_point_type) |
| 6227 | << DestTy; |
| 6228 | return CK_IntegralCast; |
| 6229 | case Type::STK_CPointer: |
| 6230 | case Type::STK_ObjCObjectPointer: |
| 6231 | case Type::STK_BlockPointer: |
| 6232 | case Type::STK_MemberPointer: |
| 6233 | llvm_unreachable("illegal cast to pointer type" ); |
| 6234 | } |
| 6235 | llvm_unreachable("Should have returned before this" ); |
| 6236 | |
| 6237 | case Type::STK_Bool: // casting from bool is like casting from an integer |
| 6238 | case Type::STK_Integral: |
| 6239 | switch (DestTy->getScalarTypeKind()) { |
| 6240 | case Type::STK_CPointer: |
| 6241 | case Type::STK_ObjCObjectPointer: |
| 6242 | case Type::STK_BlockPointer: |
| 6243 | if (Src.get()->isNullPointerConstant(Context, |
| 6244 | Expr::NPC_ValueDependentIsNull)) |
| 6245 | return CK_NullToPointer; |
| 6246 | return CK_IntegralToPointer; |
| 6247 | case Type::STK_Bool: |
| 6248 | return CK_IntegralToBoolean; |
| 6249 | case Type::STK_Integral: |
| 6250 | return CK_IntegralCast; |
| 6251 | case Type::STK_Floating: |
| 6252 | return CK_IntegralToFloating; |
| 6253 | case Type::STK_IntegralComplex: |
| 6254 | Src = ImpCastExprToType(Src.get(), |
| 6255 | DestTy->castAs<ComplexType>()->getElementType(), |
| 6256 | CK_IntegralCast); |
| 6257 | return CK_IntegralRealToComplex; |
| 6258 | case Type::STK_FloatingComplex: |
| 6259 | Src = ImpCastExprToType(Src.get(), |
| 6260 | DestTy->castAs<ComplexType>()->getElementType(), |
| 6261 | CK_IntegralToFloating); |
| 6262 | return CK_FloatingRealToComplex; |
| 6263 | case Type::STK_MemberPointer: |
| 6264 | llvm_unreachable("member pointer type in C" ); |
| 6265 | case Type::STK_FixedPoint: |
| 6266 | return CK_IntegralToFixedPoint; |
| 6267 | } |
| 6268 | llvm_unreachable("Should have returned before this" ); |
| 6269 | |
| 6270 | case Type::STK_Floating: |
| 6271 | switch (DestTy->getScalarTypeKind()) { |
| 6272 | case Type::STK_Floating: |
| 6273 | return CK_FloatingCast; |
| 6274 | case Type::STK_Bool: |
| 6275 | return CK_FloatingToBoolean; |
| 6276 | case Type::STK_Integral: |
| 6277 | return CK_FloatingToIntegral; |
| 6278 | case Type::STK_FloatingComplex: |
| 6279 | Src = ImpCastExprToType(Src.get(), |
| 6280 | DestTy->castAs<ComplexType>()->getElementType(), |
| 6281 | CK_FloatingCast); |
| 6282 | return CK_FloatingRealToComplex; |
| 6283 | case Type::STK_IntegralComplex: |
| 6284 | Src = ImpCastExprToType(Src.get(), |
| 6285 | DestTy->castAs<ComplexType>()->getElementType(), |
| 6286 | CK_FloatingToIntegral); |
| 6287 | return CK_IntegralRealToComplex; |
| 6288 | case Type::STK_CPointer: |
| 6289 | case Type::STK_ObjCObjectPointer: |
| 6290 | case Type::STK_BlockPointer: |
| 6291 | llvm_unreachable("valid float->pointer cast?" ); |
| 6292 | case Type::STK_MemberPointer: |
| 6293 | llvm_unreachable("member pointer type in C" ); |
| 6294 | case Type::STK_FixedPoint: |
| 6295 | Diag(Src.get()->getExprLoc(), |
| 6296 | diag::err_unimplemented_conversion_with_fixed_point_type) |
| 6297 | << SrcTy; |
| 6298 | return CK_IntegralCast; |
| 6299 | } |
| 6300 | llvm_unreachable("Should have returned before this" ); |
| 6301 | |
| 6302 | case Type::STK_FloatingComplex: |
| 6303 | switch (DestTy->getScalarTypeKind()) { |
| 6304 | case Type::STK_FloatingComplex: |
| 6305 | return CK_FloatingComplexCast; |
| 6306 | case Type::STK_IntegralComplex: |
| 6307 | return CK_FloatingComplexToIntegralComplex; |
| 6308 | case Type::STK_Floating: { |
| 6309 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
| 6310 | if (Context.hasSameType(ET, DestTy)) |
| 6311 | return CK_FloatingComplexToReal; |
| 6312 | Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); |
| 6313 | return CK_FloatingCast; |
| 6314 | } |
| 6315 | case Type::STK_Bool: |
| 6316 | return CK_FloatingComplexToBoolean; |
| 6317 | case Type::STK_Integral: |
| 6318 | Src = ImpCastExprToType(Src.get(), |
| 6319 | SrcTy->castAs<ComplexType>()->getElementType(), |
| 6320 | CK_FloatingComplexToReal); |
| 6321 | return CK_FloatingToIntegral; |
| 6322 | case Type::STK_CPointer: |
| 6323 | case Type::STK_ObjCObjectPointer: |
| 6324 | case Type::STK_BlockPointer: |
| 6325 | llvm_unreachable("valid complex float->pointer cast?" ); |
| 6326 | case Type::STK_MemberPointer: |
| 6327 | llvm_unreachable("member pointer type in C" ); |
| 6328 | case Type::STK_FixedPoint: |
| 6329 | Diag(Src.get()->getExprLoc(), |
| 6330 | diag::err_unimplemented_conversion_with_fixed_point_type) |
| 6331 | << SrcTy; |
| 6332 | return CK_IntegralCast; |
| 6333 | } |
| 6334 | llvm_unreachable("Should have returned before this" ); |
| 6335 | |
| 6336 | case Type::STK_IntegralComplex: |
| 6337 | switch (DestTy->getScalarTypeKind()) { |
| 6338 | case Type::STK_FloatingComplex: |
| 6339 | return CK_IntegralComplexToFloatingComplex; |
| 6340 | case Type::STK_IntegralComplex: |
| 6341 | return CK_IntegralComplexCast; |
| 6342 | case Type::STK_Integral: { |
| 6343 | QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); |
| 6344 | if (Context.hasSameType(ET, DestTy)) |
| 6345 | return CK_IntegralComplexToReal; |
| 6346 | Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); |
| 6347 | return CK_IntegralCast; |
| 6348 | } |
| 6349 | case Type::STK_Bool: |
| 6350 | return CK_IntegralComplexToBoolean; |
| 6351 | case Type::STK_Floating: |
| 6352 | Src = ImpCastExprToType(Src.get(), |
| 6353 | SrcTy->castAs<ComplexType>()->getElementType(), |
| 6354 | CK_IntegralComplexToReal); |
| 6355 | return CK_IntegralToFloating; |
| 6356 | case Type::STK_CPointer: |
| 6357 | case Type::STK_ObjCObjectPointer: |
| 6358 | case Type::STK_BlockPointer: |
| 6359 | llvm_unreachable("valid complex int->pointer cast?" ); |
| 6360 | case Type::STK_MemberPointer: |
| 6361 | llvm_unreachable("member pointer type in C" ); |
| 6362 | case Type::STK_FixedPoint: |
| 6363 | Diag(Src.get()->getExprLoc(), |
| 6364 | diag::err_unimplemented_conversion_with_fixed_point_type) |
| 6365 | << SrcTy; |
| 6366 | return CK_IntegralCast; |
| 6367 | } |
| 6368 | llvm_unreachable("Should have returned before this" ); |
| 6369 | } |
| 6370 | |
| 6371 | llvm_unreachable("Unhandled scalar cast" ); |
| 6372 | } |
| 6373 | |
| 6374 | static bool breakDownVectorType(QualType type, uint64_t &len, |
| 6375 | QualType &eltType) { |
| 6376 | // Vectors are simple. |
| 6377 | if (const VectorType *vecType = type->getAs<VectorType>()) { |
| 6378 | len = vecType->getNumElements(); |
| 6379 | eltType = vecType->getElementType(); |
| 6380 | assert(eltType->isScalarType()); |
| 6381 | return true; |
| 6382 | } |
| 6383 | |
| 6384 | // We allow lax conversion to and from non-vector types, but only if |
| 6385 | // they're real types (i.e. non-complex, non-pointer scalar types). |
| 6386 | if (!type->isRealType()) return false; |
| 6387 | |
| 6388 | len = 1; |
| 6389 | eltType = type; |
| 6390 | return true; |
| 6391 | } |
| 6392 | |
| 6393 | /// Are the two types lax-compatible vector types? That is, given |
| 6394 | /// that one of them is a vector, do they have equal storage sizes, |
| 6395 | /// where the storage size is the number of elements times the element |
| 6396 | /// size? |
| 6397 | /// |
| 6398 | /// This will also return false if either of the types is neither a |
| 6399 | /// vector nor a real type. |
| 6400 | bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { |
| 6401 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
| 6402 | |
| 6403 | // Disallow lax conversions between scalars and ExtVectors (these |
| 6404 | // conversions are allowed for other vector types because common headers |
| 6405 | // depend on them). Most scalar OP ExtVector cases are handled by the |
| 6406 | // splat path anyway, which does what we want (convert, not bitcast). |
| 6407 | // What this rules out for ExtVectors is crazy things like char4*float. |
| 6408 | if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; |
| 6409 | if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; |
| 6410 | |
| 6411 | uint64_t srcLen, destLen; |
| 6412 | QualType srcEltTy, destEltTy; |
| 6413 | if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; |
| 6414 | if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; |
| 6415 | |
| 6416 | // ASTContext::getTypeSize will return the size rounded up to a |
| 6417 | // power of 2, so instead of using that, we need to use the raw |
| 6418 | // element size multiplied by the element count. |
| 6419 | uint64_t srcEltSize = Context.getTypeSize(srcEltTy); |
| 6420 | uint64_t destEltSize = Context.getTypeSize(destEltTy); |
| 6421 | |
| 6422 | return (srcLen * srcEltSize == destLen * destEltSize); |
| 6423 | } |
| 6424 | |
| 6425 | /// Is this a legal conversion between two types, one of which is |
| 6426 | /// known to be a vector type? |
| 6427 | bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { |
| 6428 | assert(destTy->isVectorType() || srcTy->isVectorType()); |
| 6429 | |
| 6430 | if (!Context.getLangOpts().LaxVectorConversions) |
| 6431 | return false; |
| 6432 | return areLaxCompatibleVectorTypes(srcTy, destTy); |
| 6433 | } |
| 6434 | |
| 6435 | bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, |
| 6436 | CastKind &Kind) { |
| 6437 | assert(VectorTy->isVectorType() && "Not a vector type!" ); |
| 6438 | |
| 6439 | if (Ty->isVectorType() || Ty->isIntegralType(Context)) { |
| 6440 | if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) |
| 6441 | return Diag(R.getBegin(), |
| 6442 | Ty->isVectorType() ? |
| 6443 | diag::err_invalid_conversion_between_vectors : |
| 6444 | diag::err_invalid_conversion_between_vector_and_integer) |
| 6445 | << VectorTy << Ty << R; |
| 6446 | } else |
| 6447 | return Diag(R.getBegin(), |
| 6448 | diag::err_invalid_conversion_between_vector_and_scalar) |
| 6449 | << VectorTy << Ty << R; |
| 6450 | |
| 6451 | Kind = CK_BitCast; |
| 6452 | return false; |
| 6453 | } |
| 6454 | |
| 6455 | ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { |
| 6456 | QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); |
| 6457 | |
| 6458 | if (DestElemTy == SplattedExpr->getType()) |
| 6459 | return SplattedExpr; |
| 6460 | |
| 6461 | assert(DestElemTy->isFloatingType() || |
| 6462 | DestElemTy->isIntegralOrEnumerationType()); |
| 6463 | |
| 6464 | CastKind CK; |
| 6465 | if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { |
| 6466 | // OpenCL requires that we convert `true` boolean expressions to -1, but |
| 6467 | // only when splatting vectors. |
| 6468 | if (DestElemTy->isFloatingType()) { |
| 6469 | // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast |
| 6470 | // in two steps: boolean to signed integral, then to floating. |
| 6471 | ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, |
| 6472 | CK_BooleanToSignedIntegral); |
| 6473 | SplattedExpr = CastExprRes.get(); |
| 6474 | CK = CK_IntegralToFloating; |
| 6475 | } else { |
| 6476 | CK = CK_BooleanToSignedIntegral; |
| 6477 | } |
| 6478 | } else { |
| 6479 | ExprResult CastExprRes = SplattedExpr; |
| 6480 | CK = PrepareScalarCast(CastExprRes, DestElemTy); |
| 6481 | if (CastExprRes.isInvalid()) |
| 6482 | return ExprError(); |
| 6483 | SplattedExpr = CastExprRes.get(); |
| 6484 | } |
| 6485 | return ImpCastExprToType(SplattedExpr, DestElemTy, CK); |
| 6486 | } |
| 6487 | |
| 6488 | ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, |
| 6489 | Expr *CastExpr, CastKind &Kind) { |
| 6490 | assert(DestTy->isExtVectorType() && "Not an extended vector type!" ); |
| 6491 | |
| 6492 | QualType SrcTy = CastExpr->getType(); |
| 6493 | |
| 6494 | // If SrcTy is a VectorType, the total size must match to explicitly cast to |
| 6495 | // an ExtVectorType. |
| 6496 | // In OpenCL, casts between vectors of different types are not allowed. |
| 6497 | // (See OpenCL 6.2). |
| 6498 | if (SrcTy->isVectorType()) { |
| 6499 | if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || |
| 6500 | (getLangOpts().OpenCL && |
| 6501 | !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { |
| 6502 | Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) |
| 6503 | << DestTy << SrcTy << R; |
| 6504 | return ExprError(); |
| 6505 | } |
| 6506 | Kind = CK_BitCast; |
| 6507 | return CastExpr; |
| 6508 | } |
| 6509 | |
| 6510 | // All non-pointer scalars can be cast to ExtVector type. The appropriate |
| 6511 | // conversion will take place first from scalar to elt type, and then |
| 6512 | // splat from elt type to vector. |
| 6513 | if (SrcTy->isPointerType()) |
| 6514 | return Diag(R.getBegin(), |
| 6515 | diag::err_invalid_conversion_between_vector_and_scalar) |
| 6516 | << DestTy << SrcTy << R; |
| 6517 | |
| 6518 | Kind = CK_VectorSplat; |
| 6519 | return prepareVectorSplat(DestTy, CastExpr); |
| 6520 | } |
| 6521 | |
| 6522 | ExprResult |
| 6523 | Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, |
| 6524 | Declarator &D, ParsedType &Ty, |
| 6525 | SourceLocation RParenLoc, Expr *CastExpr) { |
| 6526 | assert(!D.isInvalidType() && (CastExpr != nullptr) && |
| 6527 | "ActOnCastExpr(): missing type or expr" ); |
| 6528 | |
| 6529 | TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); |
| 6530 | if (D.isInvalidType()) |
| 6531 | return ExprError(); |
| 6532 | |
| 6533 | if (getLangOpts().CPlusPlus) { |
| 6534 | // Check that there are no default arguments (C++ only). |
| 6535 | CheckExtraCXXDefaultArguments(D); |
| 6536 | } else { |
| 6537 | // Make sure any TypoExprs have been dealt with. |
| 6538 | ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); |
| 6539 | if (!Res.isUsable()) |
| 6540 | return ExprError(); |
| 6541 | CastExpr = Res.get(); |
| 6542 | } |
| 6543 | |
| 6544 | checkUnusedDeclAttributes(D); |
| 6545 | |
| 6546 | QualType castType = castTInfo->getType(); |
| 6547 | Ty = CreateParsedType(castType, castTInfo); |
| 6548 | |
| 6549 | bool isVectorLiteral = false; |
| 6550 | |
| 6551 | // Check for an altivec or OpenCL literal, |
| 6552 | // i.e. all the elements are integer constants. |
| 6553 | ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); |
| 6554 | ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); |
| 6555 | if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) |
| 6556 | && castType->isVectorType() && (PE || PLE)) { |
| 6557 | if (PLE && PLE->getNumExprs() == 0) { |
| 6558 | Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); |
| 6559 | return ExprError(); |
| 6560 | } |
| 6561 | if (PE || PLE->getNumExprs() == 1) { |
| 6562 | Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); |
| 6563 | if (!E->getType()->isVectorType()) |
| 6564 | isVectorLiteral = true; |
| 6565 | } |
| 6566 | else |
| 6567 | isVectorLiteral = true; |
| 6568 | } |
| 6569 | |
| 6570 | // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' |
| 6571 | // then handle it as such. |
| 6572 | if (isVectorLiteral) |
| 6573 | return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); |
| 6574 | |
| 6575 | // If the Expr being casted is a ParenListExpr, handle it specially. |
| 6576 | // This is not an AltiVec-style cast, so turn the ParenListExpr into a |
| 6577 | // sequence of BinOp comma operators. |
| 6578 | if (isa<ParenListExpr>(CastExpr)) { |
| 6579 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); |
| 6580 | if (Result.isInvalid()) return ExprError(); |
| 6581 | CastExpr = Result.get(); |
| 6582 | } |
| 6583 | |
| 6584 | if (getLangOpts().CPlusPlus && !castType->isVoidType() && |
| 6585 | !getSourceManager().isInSystemMacro(LParenLoc)) |
| 6586 | Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); |
| 6587 | |
| 6588 | CheckTollFreeBridgeCast(castType, CastExpr); |
| 6589 | |
| 6590 | CheckObjCBridgeRelatedCast(castType, CastExpr); |
| 6591 | |
| 6592 | DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); |
| 6593 | |
| 6594 | return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); |
| 6595 | } |
| 6596 | |
| 6597 | ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, |
| 6598 | SourceLocation RParenLoc, Expr *E, |
| 6599 | TypeSourceInfo *TInfo) { |
| 6600 | assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && |
| 6601 | "Expected paren or paren list expression" ); |
| 6602 | |
| 6603 | Expr **exprs; |
| 6604 | unsigned numExprs; |
| 6605 | Expr *subExpr; |
| 6606 | SourceLocation LiteralLParenLoc, LiteralRParenLoc; |
| 6607 | if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { |
| 6608 | LiteralLParenLoc = PE->getLParenLoc(); |
| 6609 | LiteralRParenLoc = PE->getRParenLoc(); |
| 6610 | exprs = PE->getExprs(); |
| 6611 | numExprs = PE->getNumExprs(); |
| 6612 | } else { // isa<ParenExpr> by assertion at function entrance |
| 6613 | LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); |
| 6614 | LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); |
| 6615 | subExpr = cast<ParenExpr>(E)->getSubExpr(); |
| 6616 | exprs = &subExpr; |
| 6617 | numExprs = 1; |
| 6618 | } |
| 6619 | |
| 6620 | QualType Ty = TInfo->getType(); |
| 6621 | assert(Ty->isVectorType() && "Expected vector type" ); |
| 6622 | |
| 6623 | SmallVector<Expr *, 8> initExprs; |
| 6624 | const VectorType *VTy = Ty->getAs<VectorType>(); |
| 6625 | unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); |
| 6626 | |
| 6627 | // '(...)' form of vector initialization in AltiVec: the number of |
| 6628 | // initializers must be one or must match the size of the vector. |
| 6629 | // If a single value is specified in the initializer then it will be |
| 6630 | // replicated to all the components of the vector |
| 6631 | if (VTy->getVectorKind() == VectorType::AltiVecVector) { |
| 6632 | // The number of initializers must be one or must match the size of the |
| 6633 | // vector. If a single value is specified in the initializer then it will |
| 6634 | // be replicated to all the components of the vector |
| 6635 | if (numExprs == 1) { |
| 6636 | QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); |
| 6637 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); |
| 6638 | if (Literal.isInvalid()) |
| 6639 | return ExprError(); |
| 6640 | Literal = ImpCastExprToType(Literal.get(), ElemTy, |
| 6641 | PrepareScalarCast(Literal, ElemTy)); |
| 6642 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); |
| 6643 | } |
| 6644 | else if (numExprs < numElems) { |
| 6645 | Diag(E->getExprLoc(), |
| 6646 | diag::err_incorrect_number_of_vector_initializers); |
| 6647 | return ExprError(); |
| 6648 | } |
| 6649 | else |
| 6650 | initExprs.append(exprs, exprs + numExprs); |
| 6651 | } |
| 6652 | else { |
| 6653 | // For OpenCL, when the number of initializers is a single value, |
| 6654 | // it will be replicated to all components of the vector. |
| 6655 | if (getLangOpts().OpenCL && |
| 6656 | VTy->getVectorKind() == VectorType::GenericVector && |
| 6657 | numExprs == 1) { |
| 6658 | QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); |
| 6659 | ExprResult Literal = DefaultLvalueConversion(exprs[0]); |
| 6660 | if (Literal.isInvalid()) |
| 6661 | return ExprError(); |
| 6662 | Literal = ImpCastExprToType(Literal.get(), ElemTy, |
| 6663 | PrepareScalarCast(Literal, ElemTy)); |
| 6664 | return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); |
| 6665 | } |
| 6666 | |
| 6667 | initExprs.append(exprs, exprs + numExprs); |
| 6668 | } |
| 6669 | // FIXME: This means that pretty-printing the final AST will produce curly |
| 6670 | // braces instead of the original commas. |
| 6671 | InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, |
| 6672 | initExprs, LiteralRParenLoc); |
| 6673 | initE->setType(Ty); |
| 6674 | return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); |
| 6675 | } |
| 6676 | |
| 6677 | /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn |
| 6678 | /// the ParenListExpr into a sequence of comma binary operators. |
| 6679 | ExprResult |
| 6680 | Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { |
| 6681 | ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); |
| 6682 | if (!E) |
| 6683 | return OrigExpr; |
| 6684 | |
| 6685 | ExprResult Result(E->getExpr(0)); |
| 6686 | |
| 6687 | for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) |
| 6688 | Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), |
| 6689 | E->getExpr(i)); |
| 6690 | |
| 6691 | if (Result.isInvalid()) return ExprError(); |
| 6692 | |
| 6693 | return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); |
| 6694 | } |
| 6695 | |
| 6696 | ExprResult Sema::ActOnParenListExpr(SourceLocation L, |
| 6697 | SourceLocation R, |
| 6698 | MultiExprArg Val) { |
| 6699 | return ParenListExpr::Create(Context, L, Val, R); |
| 6700 | } |
| 6701 | |
| 6702 | /// Emit a specialized diagnostic when one expression is a null pointer |
| 6703 | /// constant and the other is not a pointer. Returns true if a diagnostic is |
| 6704 | /// emitted. |
| 6705 | bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, |
| 6706 | SourceLocation QuestionLoc) { |
| 6707 | Expr *NullExpr = LHSExpr; |
| 6708 | Expr *NonPointerExpr = RHSExpr; |
| 6709 | Expr::NullPointerConstantKind NullKind = |
| 6710 | NullExpr->isNullPointerConstant(Context, |
| 6711 | Expr::NPC_ValueDependentIsNotNull); |
| 6712 | |
| 6713 | if (NullKind == Expr::NPCK_NotNull) { |
| 6714 | NullExpr = RHSExpr; |
| 6715 | NonPointerExpr = LHSExpr; |
| 6716 | NullKind = |
| 6717 | NullExpr->isNullPointerConstant(Context, |
| 6718 | Expr::NPC_ValueDependentIsNotNull); |
| 6719 | } |
| 6720 | |
| 6721 | if (NullKind == Expr::NPCK_NotNull) |
| 6722 | return false; |
| 6723 | |
| 6724 | if (NullKind == Expr::NPCK_ZeroExpression) |
| 6725 | return false; |
| 6726 | |
| 6727 | if (NullKind == Expr::NPCK_ZeroLiteral) { |
| 6728 | // In this case, check to make sure that we got here from a "NULL" |
| 6729 | // string in the source code. |
| 6730 | NullExpr = NullExpr->IgnoreParenImpCasts(); |
| 6731 | SourceLocation loc = NullExpr->getExprLoc(); |
| 6732 | if (!findMacroSpelling(loc, "NULL" )) |
| 6733 | return false; |
| 6734 | } |
| 6735 | |
| 6736 | int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); |
| 6737 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) |
| 6738 | << NonPointerExpr->getType() << DiagType |
| 6739 | << NonPointerExpr->getSourceRange(); |
| 6740 | return true; |
| 6741 | } |
| 6742 | |
| 6743 | /// Return false if the condition expression is valid, true otherwise. |
| 6744 | static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { |
| 6745 | QualType CondTy = Cond->getType(); |
| 6746 | |
| 6747 | // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. |
| 6748 | if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { |
| 6749 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) |
| 6750 | << CondTy << Cond->getSourceRange(); |
| 6751 | return true; |
| 6752 | } |
| 6753 | |
| 6754 | // C99 6.5.15p2 |
| 6755 | if (CondTy->isScalarType()) return false; |
| 6756 | |
| 6757 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) |
| 6758 | << CondTy << Cond->getSourceRange(); |
| 6759 | return true; |
| 6760 | } |
| 6761 | |
| 6762 | /// Handle when one or both operands are void type. |
| 6763 | static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, |
| 6764 | ExprResult &RHS) { |
| 6765 | Expr *LHSExpr = LHS.get(); |
| 6766 | Expr *RHSExpr = RHS.get(); |
| 6767 | |
| 6768 | if (!LHSExpr->getType()->isVoidType()) |
| 6769 | S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) |
| 6770 | << RHSExpr->getSourceRange(); |
| 6771 | if (!RHSExpr->getType()->isVoidType()) |
| 6772 | S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) |
| 6773 | << LHSExpr->getSourceRange(); |
| 6774 | LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); |
| 6775 | RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); |
| 6776 | return S.Context.VoidTy; |
| 6777 | } |
| 6778 | |
| 6779 | /// Return false if the NullExpr can be promoted to PointerTy, |
| 6780 | /// true otherwise. |
| 6781 | static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, |
| 6782 | QualType PointerTy) { |
| 6783 | if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || |
| 6784 | !NullExpr.get()->isNullPointerConstant(S.Context, |
| 6785 | Expr::NPC_ValueDependentIsNull)) |
| 6786 | return true; |
| 6787 | |
| 6788 | NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); |
| 6789 | return false; |
| 6790 | } |
| 6791 | |
| 6792 | /// Checks compatibility between two pointers and return the resulting |
| 6793 | /// type. |
| 6794 | static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, |
| 6795 | ExprResult &RHS, |
| 6796 | SourceLocation Loc) { |
| 6797 | QualType LHSTy = LHS.get()->getType(); |
| 6798 | QualType RHSTy = RHS.get()->getType(); |
| 6799 | |
| 6800 | if (S.Context.hasSameType(LHSTy, RHSTy)) { |
| 6801 | // Two identical pointers types are always compatible. |
| 6802 | return LHSTy; |
| 6803 | } |
| 6804 | |
| 6805 | QualType lhptee, rhptee; |
| 6806 | |
| 6807 | // Get the pointee types. |
| 6808 | bool IsBlockPointer = false; |
| 6809 | if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { |
| 6810 | lhptee = LHSBTy->getPointeeType(); |
| 6811 | rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); |
| 6812 | IsBlockPointer = true; |
| 6813 | } else { |
| 6814 | lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); |
| 6815 | rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); |
| 6816 | } |
| 6817 | |
| 6818 | // C99 6.5.15p6: If both operands are pointers to compatible types or to |
| 6819 | // differently qualified versions of compatible types, the result type is |
| 6820 | // a pointer to an appropriately qualified version of the composite |
| 6821 | // type. |
| 6822 | |
| 6823 | // Only CVR-qualifiers exist in the standard, and the differently-qualified |
| 6824 | // clause doesn't make sense for our extensions. E.g. address space 2 should |
| 6825 | // be incompatible with address space 3: they may live on different devices or |
| 6826 | // anything. |
| 6827 | Qualifiers lhQual = lhptee.getQualifiers(); |
| 6828 | Qualifiers rhQual = rhptee.getQualifiers(); |
| 6829 | |
| 6830 | LangAS ResultAddrSpace = LangAS::Default; |
| 6831 | LangAS LAddrSpace = lhQual.getAddressSpace(); |
| 6832 | LangAS RAddrSpace = rhQual.getAddressSpace(); |
| 6833 | |
| 6834 | // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address |
| 6835 | // spaces is disallowed. |
| 6836 | if (lhQual.isAddressSpaceSupersetOf(rhQual)) |
| 6837 | ResultAddrSpace = LAddrSpace; |
| 6838 | else if (rhQual.isAddressSpaceSupersetOf(lhQual)) |
| 6839 | ResultAddrSpace = RAddrSpace; |
| 6840 | else { |
| 6841 | S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
| 6842 | << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() |
| 6843 | << RHS.get()->getSourceRange(); |
| 6844 | return QualType(); |
| 6845 | } |
| 6846 | |
| 6847 | unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); |
| 6848 | auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; |
| 6849 | lhQual.removeCVRQualifiers(); |
| 6850 | rhQual.removeCVRQualifiers(); |
| 6851 | |
| 6852 | // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers |
| 6853 | // (C99 6.7.3) for address spaces. We assume that the check should behave in |
| 6854 | // the same manner as it's defined for CVR qualifiers, so for OpenCL two |
| 6855 | // qual types are compatible iff |
| 6856 | // * corresponded types are compatible |
| 6857 | // * CVR qualifiers are equal |
| 6858 | // * address spaces are equal |
| 6859 | // Thus for conditional operator we merge CVR and address space unqualified |
| 6860 | // pointees and if there is a composite type we return a pointer to it with |
| 6861 | // merged qualifiers. |
| 6862 | LHSCastKind = |
| 6863 | LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
| 6864 | RHSCastKind = |
| 6865 | RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; |
| 6866 | lhQual.removeAddressSpace(); |
| 6867 | rhQual.removeAddressSpace(); |
| 6868 | |
| 6869 | lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); |
| 6870 | rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); |
| 6871 | |
| 6872 | QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); |
| 6873 | |
| 6874 | if (CompositeTy.isNull()) { |
| 6875 | // In this situation, we assume void* type. No especially good |
| 6876 | // reason, but this is what gcc does, and we do have to pick |
| 6877 | // to get a consistent AST. |
| 6878 | QualType incompatTy; |
| 6879 | incompatTy = S.Context.getPointerType( |
| 6880 | S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); |
| 6881 | LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); |
| 6882 | RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); |
| 6883 | |
| 6884 | // FIXME: For OpenCL the warning emission and cast to void* leaves a room |
| 6885 | // for casts between types with incompatible address space qualifiers. |
| 6886 | // For the following code the compiler produces casts between global and |
| 6887 | // local address spaces of the corresponded innermost pointees: |
| 6888 | // local int *global *a; |
| 6889 | // global int *global *b; |
| 6890 | // a = (0 ? a : b); // see C99 6.5.16.1.p1. |
| 6891 | S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) |
| 6892 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 6893 | << RHS.get()->getSourceRange(); |
| 6894 | |
| 6895 | return incompatTy; |
| 6896 | } |
| 6897 | |
| 6898 | // The pointer types are compatible. |
| 6899 | // In case of OpenCL ResultTy should have the address space qualifier |
| 6900 | // which is a superset of address spaces of both the 2nd and the 3rd |
| 6901 | // operands of the conditional operator. |
| 6902 | QualType ResultTy = [&, ResultAddrSpace]() { |
| 6903 | if (S.getLangOpts().OpenCL) { |
| 6904 | Qualifiers CompositeQuals = CompositeTy.getQualifiers(); |
| 6905 | CompositeQuals.setAddressSpace(ResultAddrSpace); |
| 6906 | return S.Context |
| 6907 | .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) |
| 6908 | .withCVRQualifiers(MergedCVRQual); |
| 6909 | } |
| 6910 | return CompositeTy.withCVRQualifiers(MergedCVRQual); |
| 6911 | }(); |
| 6912 | if (IsBlockPointer) |
| 6913 | ResultTy = S.Context.getBlockPointerType(ResultTy); |
| 6914 | else { |
| 6915 | ASTContext::PointerInterpretationKind PIK = ASTContext::PIK_Default; |
| 6916 | if (LHSTy->isCHERICapabilityType(S.Context) |
| 6917 | || RHSTy->isCHERICapabilityType(S.Context)) { |
| 6918 | PIK = ASTContext::PIK_Capability; |
| 6919 | } |
| 6920 | ResultTy = S.Context.getPointerType(ResultTy, PIK); |
| 6921 | } |
| 6922 | |
| 6923 | LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); |
| 6924 | RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); |
| 6925 | return ResultTy; |
| 6926 | } |
| 6927 | |
| 6928 | /// Return the resulting type when the operands are both block pointers. |
| 6929 | static QualType checkConditionalBlockPointerCompatibility(Sema &S, |
| 6930 | ExprResult &LHS, |
| 6931 | ExprResult &RHS, |
| 6932 | SourceLocation Loc) { |
| 6933 | QualType LHSTy = LHS.get()->getType(); |
| 6934 | QualType RHSTy = RHS.get()->getType(); |
| 6935 | |
| 6936 | if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { |
| 6937 | if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { |
| 6938 | QualType destType = S.Context.getPointerType(S.Context.VoidTy); |
| 6939 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); |
| 6940 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); |
| 6941 | return destType; |
| 6942 | } |
| 6943 | S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) |
| 6944 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 6945 | << RHS.get()->getSourceRange(); |
| 6946 | return QualType(); |
| 6947 | } |
| 6948 | |
| 6949 | // We have 2 block pointer types. |
| 6950 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
| 6951 | } |
| 6952 | |
| 6953 | /// Return the resulting type when the operands are both pointers. |
| 6954 | static QualType |
| 6955 | checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, |
| 6956 | ExprResult &RHS, |
| 6957 | SourceLocation Loc) { |
| 6958 | // get the pointer types |
| 6959 | QualType LHSTy = LHS.get()->getType(); |
| 6960 | QualType RHSTy = RHS.get()->getType(); |
| 6961 | |
| 6962 | // get the "pointed to" types |
| 6963 | QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); |
| 6964 | QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); |
| 6965 | |
| 6966 | // Get the cast kind to use for adding qualifiers |
| 6967 | // XXXAR: There should probably be a CK_CHERICapabilityToPointer here? |
| 6968 | CastKind NopCastKind = (lhptee.getAddressSpace() == rhptee.getAddressSpace()) |
| 6969 | ? CK_NoOp : CK_AddressSpaceConversion; |
| 6970 | |
| 6971 | // ignore qualifiers on void (C99 6.5.15p3, clause 6) |
| 6972 | if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { |
| 6973 | // Figure out necessary qualifiers (C99 6.5.15p6) |
| 6974 | QualType destPointee |
| 6975 | = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); |
| 6976 | QualType destType = S.Context.getPointerType(destPointee, |
| 6977 | RHSTy->isCHERICapabilityType(S.Context) ? ASTContext::PIK_Capability : ASTContext::PIK_Default); |
| 6978 | // Add qualifiers if necessary. |
| 6979 | LHS = S.ImpCastExprToType(LHS.get(), destType, NopCastKind); |
| 6980 | // Promote to void*. |
| 6981 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); |
| 6982 | return destType; |
| 6983 | } |
| 6984 | if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { |
| 6985 | QualType destPointee |
| 6986 | = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); |
| 6987 | QualType destType = S.Context.getPointerType(destPointee, |
| 6988 | LHSTy->isCHERICapabilityType(S.Context) ? ASTContext::PIK_Capability : ASTContext::PIK_Default); |
| 6989 | // Add qualifiers if necessary. |
| 6990 | RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); |
| 6991 | // Promote to void*. |
| 6992 | LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); |
| 6993 | return destType; |
| 6994 | } |
| 6995 | |
| 6996 | return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); |
| 6997 | } |
| 6998 | |
| 6999 | /// Return false if the first expression is not an integer and the second |
| 7000 | /// expression is not a pointer, true otherwise. |
| 7001 | static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, |
| 7002 | Expr* PointerExpr, SourceLocation Loc, |
| 7003 | bool IsIntFirstExpr) { |
| 7004 | if (!PointerExpr->getType()->isPointerType() || |
| 7005 | !Int.get()->getType()->isIntegerType()) |
| 7006 | return false; |
| 7007 | |
| 7008 | Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; |
| 7009 | Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); |
| 7010 | |
| 7011 | S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) |
| 7012 | << Expr1->getType() << Expr2->getType() |
| 7013 | << Expr1->getSourceRange() << Expr2->getSourceRange(); |
| 7014 | Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), |
| 7015 | CK_IntegralToPointer); |
| 7016 | return true; |
| 7017 | } |
| 7018 | |
| 7019 | /// Simple conversion between integer and floating point types. |
| 7020 | /// |
| 7021 | /// Used when handling the OpenCL conditional operator where the |
| 7022 | /// condition is a vector while the other operands are scalar. |
| 7023 | /// |
| 7024 | /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar |
| 7025 | /// types are either integer or floating type. Between the two |
| 7026 | /// operands, the type with the higher rank is defined as the "result |
| 7027 | /// type". The other operand needs to be promoted to the same type. No |
| 7028 | /// other type promotion is allowed. We cannot use |
| 7029 | /// UsualArithmeticConversions() for this purpose, since it always |
| 7030 | /// promotes promotable types. |
| 7031 | static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, |
| 7032 | ExprResult &RHS, |
| 7033 | SourceLocation QuestionLoc) { |
| 7034 | LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); |
| 7035 | if (LHS.isInvalid()) |
| 7036 | return QualType(); |
| 7037 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); |
| 7038 | if (RHS.isInvalid()) |
| 7039 | return QualType(); |
| 7040 | |
| 7041 | // For conversion purposes, we ignore any qualifiers. |
| 7042 | // For example, "const float" and "float" are equivalent. |
| 7043 | QualType LHSType = |
| 7044 | S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); |
| 7045 | QualType RHSType = |
| 7046 | S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); |
| 7047 | |
| 7048 | if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { |
| 7049 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) |
| 7050 | << LHSType << LHS.get()->getSourceRange(); |
| 7051 | return QualType(); |
| 7052 | } |
| 7053 | |
| 7054 | if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { |
| 7055 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) |
| 7056 | << RHSType << RHS.get()->getSourceRange(); |
| 7057 | return QualType(); |
| 7058 | } |
| 7059 | |
| 7060 | // If both types are identical, no conversion is needed. |
| 7061 | if (LHSType == RHSType) |
| 7062 | return LHSType; |
| 7063 | |
| 7064 | // Now handle "real" floating types (i.e. float, double, long double). |
| 7065 | if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) |
| 7066 | return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, |
| 7067 | /*IsCompAssign = */ false); |
| 7068 | |
| 7069 | // Finally, we have two differing integer types. |
| 7070 | return handleIntegerConversion<doIntegralCast, doIntegralCast> |
| 7071 | (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); |
| 7072 | } |
| 7073 | |
| 7074 | /// Convert scalar operands to a vector that matches the |
| 7075 | /// condition in length. |
| 7076 | /// |
| 7077 | /// Used when handling the OpenCL conditional operator where the |
| 7078 | /// condition is a vector while the other operands are scalar. |
| 7079 | /// |
| 7080 | /// We first compute the "result type" for the scalar operands |
| 7081 | /// according to OpenCL v1.1 s6.3.i. Both operands are then converted |
| 7082 | /// into a vector of that type where the length matches the condition |
| 7083 | /// vector type. s6.11.6 requires that the element types of the result |
| 7084 | /// and the condition must have the same number of bits. |
| 7085 | static QualType |
| 7086 | OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 7087 | QualType CondTy, SourceLocation QuestionLoc) { |
| 7088 | QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); |
| 7089 | if (ResTy.isNull()) return QualType(); |
| 7090 | |
| 7091 | const VectorType *CV = CondTy->getAs<VectorType>(); |
| 7092 | assert(CV); |
| 7093 | |
| 7094 | // Determine the vector result type |
| 7095 | unsigned NumElements = CV->getNumElements(); |
| 7096 | QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); |
| 7097 | |
| 7098 | // Ensure that all types have the same number of bits |
| 7099 | if (S.Context.getTypeSize(CV->getElementType()) |
| 7100 | != S.Context.getTypeSize(ResTy)) { |
| 7101 | // Since VectorTy is created internally, it does not pretty print |
| 7102 | // with an OpenCL name. Instead, we just print a description. |
| 7103 | std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); |
| 7104 | SmallString<64> Str; |
| 7105 | llvm::raw_svector_ostream OS(Str); |
| 7106 | OS << "(vector of " << NumElements << " '" << EleTyName << "' values)" ; |
| 7107 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
| 7108 | << CondTy << OS.str(); |
| 7109 | return QualType(); |
| 7110 | } |
| 7111 | |
| 7112 | // Convert operands to the vector result type |
| 7113 | LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); |
| 7114 | RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); |
| 7115 | |
| 7116 | return VectorTy; |
| 7117 | } |
| 7118 | |
| 7119 | /// Return false if this is a valid OpenCL condition vector |
| 7120 | static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, |
| 7121 | SourceLocation QuestionLoc) { |
| 7122 | // OpenCL v1.1 s6.11.6 says the elements of the vector must be of |
| 7123 | // integral type. |
| 7124 | const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); |
| 7125 | assert(CondTy); |
| 7126 | QualType EleTy = CondTy->getElementType(); |
| 7127 | if (EleTy->isIntegerType()) return false; |
| 7128 | |
| 7129 | S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) |
| 7130 | << Cond->getType() << Cond->getSourceRange(); |
| 7131 | return true; |
| 7132 | } |
| 7133 | |
| 7134 | /// Return false if the vector condition type and the vector |
| 7135 | /// result type are compatible. |
| 7136 | /// |
| 7137 | /// OpenCL v1.1 s6.11.6 requires that both vector types have the same |
| 7138 | /// number of elements, and their element types have the same number |
| 7139 | /// of bits. |
| 7140 | static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, |
| 7141 | SourceLocation QuestionLoc) { |
| 7142 | const VectorType *CV = CondTy->getAs<VectorType>(); |
| 7143 | const VectorType *RV = VecResTy->getAs<VectorType>(); |
| 7144 | assert(CV && RV); |
| 7145 | |
| 7146 | if (CV->getNumElements() != RV->getNumElements()) { |
| 7147 | S.Diag(QuestionLoc, diag::err_conditional_vector_size) |
| 7148 | << CondTy << VecResTy; |
| 7149 | return true; |
| 7150 | } |
| 7151 | |
| 7152 | QualType CVE = CV->getElementType(); |
| 7153 | QualType RVE = RV->getElementType(); |
| 7154 | |
| 7155 | if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { |
| 7156 | S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
| 7157 | << CondTy << VecResTy; |
| 7158 | return true; |
| 7159 | } |
| 7160 | |
| 7161 | return false; |
| 7162 | } |
| 7163 | |
| 7164 | /// Return the resulting type for the conditional operator in |
| 7165 | /// OpenCL (aka "ternary selection operator", OpenCL v1.1 |
| 7166 | /// s6.3.i) when the condition is a vector type. |
| 7167 | static QualType |
| 7168 | OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, |
| 7169 | ExprResult &LHS, ExprResult &RHS, |
| 7170 | SourceLocation QuestionLoc) { |
| 7171 | Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); |
| 7172 | if (Cond.isInvalid()) |
| 7173 | return QualType(); |
| 7174 | QualType CondTy = Cond.get()->getType(); |
| 7175 | |
| 7176 | if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) |
| 7177 | return QualType(); |
| 7178 | |
| 7179 | // If either operand is a vector then find the vector type of the |
| 7180 | // result as specified in OpenCL v1.1 s6.3.i. |
| 7181 | if (LHS.get()->getType()->isVectorType() || |
| 7182 | RHS.get()->getType()->isVectorType()) { |
| 7183 | QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, |
| 7184 | /*isCompAssign*/false, |
| 7185 | /*AllowBothBool*/true, |
| 7186 | /*AllowBoolConversions*/false); |
| 7187 | if (VecResTy.isNull()) return QualType(); |
| 7188 | // The result type must match the condition type as specified in |
| 7189 | // OpenCL v1.1 s6.11.6. |
| 7190 | if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) |
| 7191 | return QualType(); |
| 7192 | return VecResTy; |
| 7193 | } |
| 7194 | |
| 7195 | // Both operands are scalar. |
| 7196 | return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); |
| 7197 | } |
| 7198 | |
| 7199 | /// Return true if the Expr is block type |
| 7200 | static bool checkBlockType(Sema &S, const Expr *E) { |
| 7201 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { |
| 7202 | QualType Ty = CE->getCallee()->getType(); |
| 7203 | if (Ty->isBlockPointerType()) { |
| 7204 | S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); |
| 7205 | return true; |
| 7206 | } |
| 7207 | } |
| 7208 | return false; |
| 7209 | } |
| 7210 | |
| 7211 | /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. |
| 7212 | /// In that case, LHS = cond. |
| 7213 | /// C99 6.5.15 |
| 7214 | QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
| 7215 | ExprResult &RHS, ExprValueKind &VK, |
| 7216 | ExprObjectKind &OK, |
| 7217 | SourceLocation QuestionLoc) { |
| 7218 | |
| 7219 | ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); |
| 7220 | if (!LHSResult.isUsable()) return QualType(); |
| 7221 | LHS = LHSResult; |
| 7222 | |
| 7223 | ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); |
| 7224 | if (!RHSResult.isUsable()) return QualType(); |
| 7225 | RHS = RHSResult; |
| 7226 | |
| 7227 | // C++ is sufficiently different to merit its own checker. |
| 7228 | if (getLangOpts().CPlusPlus) |
| 7229 | return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); |
| 7230 | |
| 7231 | VK = VK_RValue; |
| 7232 | OK = OK_Ordinary; |
| 7233 | |
| 7234 | // The OpenCL operator with a vector condition is sufficiently |
| 7235 | // different to merit its own checker. |
| 7236 | if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) |
| 7237 | return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); |
| 7238 | |
| 7239 | // First, check the condition. |
| 7240 | Cond = UsualUnaryConversions(Cond.get()); |
| 7241 | if (Cond.isInvalid()) |
| 7242 | return QualType(); |
| 7243 | if (checkCondition(*this, Cond.get(), QuestionLoc)) |
| 7244 | return QualType(); |
| 7245 | |
| 7246 | // Now check the two expressions. |
| 7247 | if (LHS.get()->getType()->isVectorType() || |
| 7248 | RHS.get()->getType()->isVectorType()) |
| 7249 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, |
| 7250 | /*AllowBothBool*/true, |
| 7251 | /*AllowBoolConversions*/false); |
| 7252 | |
| 7253 | QualType ResTy = UsualArithmeticConversions(LHS, RHS); |
| 7254 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 7255 | return QualType(); |
| 7256 | |
| 7257 | QualType LHSTy = LHS.get()->getType(); |
| 7258 | QualType RHSTy = RHS.get()->getType(); |
| 7259 | |
| 7260 | // Diagnose attempts to convert between __float128 and long double where |
| 7261 | // such conversions currently can't be handled. |
| 7262 | if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { |
| 7263 | Diag(QuestionLoc, |
| 7264 | diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy |
| 7265 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 7266 | return QualType(); |
| 7267 | } |
| 7268 | |
| 7269 | // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary |
| 7270 | // selection operator (?:). |
| 7271 | if (getLangOpts().OpenCL && |
| 7272 | (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { |
| 7273 | return QualType(); |
| 7274 | } |
| 7275 | |
| 7276 | // If both operands have arithmetic type, do the usual arithmetic conversions |
| 7277 | // to find a common type: C99 6.5.15p3,5. |
| 7278 | if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { |
| 7279 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); |
| 7280 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); |
| 7281 | |
| 7282 | return ResTy; |
| 7283 | } |
| 7284 | |
| 7285 | // If both operands are the same structure or union type, the result is that |
| 7286 | // type. |
| 7287 | if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 |
| 7288 | if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) |
| 7289 | if (LHSRT->getDecl() == RHSRT->getDecl()) |
| 7290 | // "If both the operands have structure or union type, the result has |
| 7291 | // that type." This implies that CV qualifiers are dropped. |
| 7292 | return LHSTy.getUnqualifiedType(); |
| 7293 | // FIXME: Type of conditional expression must be complete in C mode. |
| 7294 | } |
| 7295 | |
| 7296 | // C99 6.5.15p5: "If both operands have void type, the result has void type." |
| 7297 | // The following || allows only one side to be void (a GCC-ism). |
| 7298 | if (LHSTy->isVoidType() || RHSTy->isVoidType()) { |
| 7299 | return checkConditionalVoidType(*this, LHS, RHS); |
| 7300 | } |
| 7301 | |
| 7302 | // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has |
| 7303 | // the type of the other operand." |
| 7304 | if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; |
| 7305 | if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; |
| 7306 | |
| 7307 | // All objective-c pointer type analysis is done here. |
| 7308 | QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, |
| 7309 | QuestionLoc); |
| 7310 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 7311 | return QualType(); |
| 7312 | if (!compositeType.isNull()) |
| 7313 | return compositeType; |
| 7314 | |
| 7315 | |
| 7316 | // Handle block pointer types. |
| 7317 | if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) |
| 7318 | return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, |
| 7319 | QuestionLoc); |
| 7320 | |
| 7321 | // Check constraints for C object pointers types (C99 6.5.15p3,6). |
| 7322 | if (LHSTy->isPointerType() && RHSTy->isPointerType()) |
| 7323 | return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, |
| 7324 | QuestionLoc); |
| 7325 | |
| 7326 | // GCC compatibility: soften pointer/integer mismatch. Note that |
| 7327 | // null pointers have been filtered out by this point. |
| 7328 | if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, |
| 7329 | /*isIntFirstExpr=*/true)) |
| 7330 | return RHSTy; |
| 7331 | if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, |
| 7332 | /*isIntFirstExpr=*/false)) |
| 7333 | return LHSTy; |
| 7334 | |
| 7335 | // Emit a better diagnostic if one of the expressions is a null pointer |
| 7336 | // constant and the other is not a pointer type. In this case, the user most |
| 7337 | // likely forgot to take the address of the other expression. |
| 7338 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) |
| 7339 | return QualType(); |
| 7340 | |
| 7341 | // Otherwise, the operands are not compatible. |
| 7342 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
| 7343 | << LHSTy << RHSTy << LHS.get()->getSourceRange() |
| 7344 | << RHS.get()->getSourceRange(); |
| 7345 | return QualType(); |
| 7346 | } |
| 7347 | |
| 7348 | /// FindCompositeObjCPointerType - Helper method to find composite type of |
| 7349 | /// two objective-c pointer types of the two input expressions. |
| 7350 | QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, |
| 7351 | SourceLocation QuestionLoc) { |
| 7352 | QualType LHSTy = LHS.get()->getType(); |
| 7353 | QualType RHSTy = RHS.get()->getType(); |
| 7354 | |
| 7355 | // Handle things like Class and struct objc_class*. Here we case the result |
| 7356 | // to the pseudo-builtin, because that will be implicitly cast back to the |
| 7357 | // redefinition type if an attempt is made to access its fields. |
| 7358 | if (LHSTy->isObjCClassType() && |
| 7359 | (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { |
| 7360 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); |
| 7361 | return LHSTy; |
| 7362 | } |
| 7363 | if (RHSTy->isObjCClassType() && |
| 7364 | (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { |
| 7365 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); |
| 7366 | return RHSTy; |
| 7367 | } |
| 7368 | // And the same for struct objc_object* / id |
| 7369 | if (LHSTy->isObjCIdType() && |
| 7370 | (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { |
| 7371 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); |
| 7372 | return LHSTy; |
| 7373 | } |
| 7374 | if (RHSTy->isObjCIdType() && |
| 7375 | (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { |
| 7376 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); |
| 7377 | return RHSTy; |
| 7378 | } |
| 7379 | // And the same for struct objc_selector* / SEL |
| 7380 | if (Context.isObjCSelType(LHSTy) && |
| 7381 | (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { |
| 7382 | RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); |
| 7383 | return LHSTy; |
| 7384 | } |
| 7385 | if (Context.isObjCSelType(RHSTy) && |
| 7386 | (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { |
| 7387 | LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); |
| 7388 | return RHSTy; |
| 7389 | } |
| 7390 | // Check constraints for Objective-C object pointers types. |
| 7391 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { |
| 7392 | |
| 7393 | if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { |
| 7394 | // Two identical object pointer types are always compatible. |
| 7395 | return LHSTy; |
| 7396 | } |
| 7397 | const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); |
| 7398 | const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); |
| 7399 | QualType compositeType = LHSTy; |
| 7400 | |
| 7401 | // If both operands are interfaces and either operand can be |
| 7402 | // assigned to the other, use that type as the composite |
| 7403 | // type. This allows |
| 7404 | // xxx ? (A*) a : (B*) b |
| 7405 | // where B is a subclass of A. |
| 7406 | // |
| 7407 | // Additionally, as for assignment, if either type is 'id' |
| 7408 | // allow silent coercion. Finally, if the types are |
| 7409 | // incompatible then make sure to use 'id' as the composite |
| 7410 | // type so the result is acceptable for sending messages to. |
| 7411 | |
| 7412 | // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. |
| 7413 | // It could return the composite type. |
| 7414 | if (!(compositeType = |
| 7415 | Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { |
| 7416 | // Nothing more to do. |
| 7417 | } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { |
| 7418 | compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; |
| 7419 | } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { |
| 7420 | compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; |
| 7421 | } else if ((LHSTy->isObjCQualifiedIdType() || |
| 7422 | RHSTy->isObjCQualifiedIdType()) && |
| 7423 | Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { |
| 7424 | // Need to handle "id<xx>" explicitly. |
| 7425 | // GCC allows qualified id and any Objective-C type to devolve to |
| 7426 | // id. Currently localizing to here until clear this should be |
| 7427 | // part of ObjCQualifiedIdTypesAreCompatible. |
| 7428 | compositeType = Context.getObjCIdType(); |
| 7429 | } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { |
| 7430 | compositeType = Context.getObjCIdType(); |
| 7431 | } else { |
| 7432 | Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) |
| 7433 | << LHSTy << RHSTy |
| 7434 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 7435 | QualType incompatTy = Context.getObjCIdType(); |
| 7436 | LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); |
| 7437 | RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); |
| 7438 | return incompatTy; |
| 7439 | } |
| 7440 | // The object pointer types are compatible. |
| 7441 | LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); |
| 7442 | RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); |
| 7443 | return compositeType; |
| 7444 | } |
| 7445 | // Check Objective-C object pointer types and 'void *' |
| 7446 | if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { |
| 7447 | if (getLangOpts().ObjCAutoRefCount) { |
| 7448 | // ARC forbids the implicit conversion of object pointers to 'void *', |
| 7449 | // so these types are not compatible. |
| 7450 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy |
| 7451 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 7452 | LHS = RHS = true; |
| 7453 | return QualType(); |
| 7454 | } |
| 7455 | QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); |
| 7456 | QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); |
| 7457 | QualType destPointee |
| 7458 | = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); |
| 7459 | QualType destType = Context.getPointerType(destPointee); |
| 7460 | // Add qualifiers if necessary. |
| 7461 | LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); |
| 7462 | // Promote to void*. |
| 7463 | RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); |
| 7464 | return destType; |
| 7465 | } |
| 7466 | if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { |
| 7467 | if (getLangOpts().ObjCAutoRefCount) { |
| 7468 | // ARC forbids the implicit conversion of object pointers to 'void *', |
| 7469 | // so these types are not compatible. |
| 7470 | Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy |
| 7471 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 7472 | LHS = RHS = true; |
| 7473 | return QualType(); |
| 7474 | } |
| 7475 | QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); |
| 7476 | QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); |
| 7477 | QualType destPointee |
| 7478 | = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); |
| 7479 | QualType destType = Context.getPointerType(destPointee); |
| 7480 | // Add qualifiers if necessary. |
| 7481 | RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); |
| 7482 | // Promote to void*. |
| 7483 | LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); |
| 7484 | return destType; |
| 7485 | } |
| 7486 | return QualType(); |
| 7487 | } |
| 7488 | |
| 7489 | /// SuggestParentheses - Emit a note with a fixit hint that wraps |
| 7490 | /// ParenRange in parentheses. |
| 7491 | static void SuggestParentheses(Sema &Self, SourceLocation Loc, |
| 7492 | const PartialDiagnostic &Note, |
| 7493 | SourceRange ParenRange) { |
| 7494 | SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); |
| 7495 | if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && |
| 7496 | EndLoc.isValid()) { |
| 7497 | Self.Diag(Loc, Note) |
| 7498 | << FixItHint::CreateInsertion(ParenRange.getBegin(), "(" ) |
| 7499 | << FixItHint::CreateInsertion(EndLoc, ")" ); |
| 7500 | } else { |
| 7501 | // We can't display the parentheses, so just show the bare note. |
| 7502 | Self.Diag(Loc, Note) << ParenRange; |
| 7503 | } |
| 7504 | } |
| 7505 | |
| 7506 | static bool IsArithmeticOp(BinaryOperatorKind Opc) { |
| 7507 | return BinaryOperator::isAdditiveOp(Opc) || |
| 7508 | BinaryOperator::isMultiplicativeOp(Opc) || |
| 7509 | BinaryOperator::isShiftOp(Opc); |
| 7510 | } |
| 7511 | |
| 7512 | /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary |
| 7513 | /// expression, either using a built-in or overloaded operator, |
| 7514 | /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side |
| 7515 | /// expression. |
| 7516 | static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, |
| 7517 | Expr **RHSExprs) { |
| 7518 | // Don't strip parenthesis: we should not warn if E is in parenthesis. |
| 7519 | E = E->IgnoreImpCasts(); |
| 7520 | E = E->IgnoreConversionOperator(); |
| 7521 | E = E->IgnoreImpCasts(); |
| 7522 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { |
| 7523 | E = MTE->GetTemporaryExpr(); |
| 7524 | E = E->IgnoreImpCasts(); |
| 7525 | } |
| 7526 | |
| 7527 | // Built-in binary operator. |
| 7528 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { |
| 7529 | if (IsArithmeticOp(OP->getOpcode())) { |
| 7530 | *Opcode = OP->getOpcode(); |
| 7531 | *RHSExprs = OP->getRHS(); |
| 7532 | return true; |
| 7533 | } |
| 7534 | } |
| 7535 | |
| 7536 | // Overloaded operator. |
| 7537 | if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { |
| 7538 | if (Call->getNumArgs() != 2) |
| 7539 | return false; |
| 7540 | |
| 7541 | // Make sure this is really a binary operator that is safe to pass into |
| 7542 | // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. |
| 7543 | OverloadedOperatorKind OO = Call->getOperator(); |
| 7544 | if (OO < OO_Plus || OO > OO_Arrow || |
| 7545 | OO == OO_PlusPlus || OO == OO_MinusMinus) |
| 7546 | return false; |
| 7547 | |
| 7548 | BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); |
| 7549 | if (IsArithmeticOp(OpKind)) { |
| 7550 | *Opcode = OpKind; |
| 7551 | *RHSExprs = Call->getArg(1); |
| 7552 | return true; |
| 7553 | } |
| 7554 | } |
| 7555 | |
| 7556 | return false; |
| 7557 | } |
| 7558 | |
| 7559 | /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type |
| 7560 | /// or is a logical expression such as (x==y) which has int type, but is |
| 7561 | /// commonly interpreted as boolean. |
| 7562 | static bool ExprLooksBoolean(Expr *E) { |
| 7563 | E = E->IgnoreParenImpCasts(); |
| 7564 | |
| 7565 | if (E->getType()->isBooleanType()) |
| 7566 | return true; |
| 7567 | if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) |
| 7568 | return OP->isComparisonOp() || OP->isLogicalOp(); |
| 7569 | if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) |
| 7570 | return OP->getOpcode() == UO_LNot; |
| 7571 | if (E->getType()->isPointerType()) |
| 7572 | return true; |
| 7573 | // FIXME: What about overloaded operator calls returning "unspecified boolean |
| 7574 | // type"s (commonly pointer-to-members)? |
| 7575 | |
| 7576 | return false; |
| 7577 | } |
| 7578 | |
| 7579 | /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator |
| 7580 | /// and binary operator are mixed in a way that suggests the programmer assumed |
| 7581 | /// the conditional operator has higher precedence, for example: |
| 7582 | /// "int x = a + someBinaryCondition ? 1 : 2". |
| 7583 | static void DiagnoseConditionalPrecedence(Sema &Self, |
| 7584 | SourceLocation OpLoc, |
| 7585 | Expr *Condition, |
| 7586 | Expr *LHSExpr, |
| 7587 | Expr *RHSExpr) { |
| 7588 | BinaryOperatorKind CondOpcode; |
| 7589 | Expr *CondRHS; |
| 7590 | |
| 7591 | if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) |
| 7592 | return; |
| 7593 | if (!ExprLooksBoolean(CondRHS)) |
| 7594 | return; |
| 7595 | |
| 7596 | // The condition is an arithmetic binary expression, with a right- |
| 7597 | // hand side that looks boolean, so warn. |
| 7598 | |
| 7599 | Self.Diag(OpLoc, diag::warn_precedence_conditional) |
| 7600 | << Condition->getSourceRange() |
| 7601 | << BinaryOperator::getOpcodeStr(CondOpcode); |
| 7602 | |
| 7603 | SuggestParentheses( |
| 7604 | Self, OpLoc, |
| 7605 | Self.PDiag(diag::note_precedence_silence) |
| 7606 | << BinaryOperator::getOpcodeStr(CondOpcode), |
| 7607 | SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); |
| 7608 | |
| 7609 | SuggestParentheses(Self, OpLoc, |
| 7610 | Self.PDiag(diag::note_precedence_conditional_first), |
| 7611 | SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); |
| 7612 | } |
| 7613 | |
| 7614 | /// Compute the nullability of a conditional expression. |
| 7615 | static QualType computeConditionalNullability(QualType ResTy, bool IsBin, |
| 7616 | QualType LHSTy, QualType RHSTy, |
| 7617 | ASTContext &Ctx) { |
| 7618 | if (!ResTy->isAnyPointerType()) |
| 7619 | return ResTy; |
| 7620 | |
| 7621 | auto GetNullability = [&Ctx](QualType Ty) { |
| 7622 | Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); |
| 7623 | if (Kind) |
| 7624 | return *Kind; |
| 7625 | return NullabilityKind::Unspecified; |
| 7626 | }; |
| 7627 | |
| 7628 | auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); |
| 7629 | NullabilityKind MergedKind; |
| 7630 | |
| 7631 | // Compute nullability of a binary conditional expression. |
| 7632 | if (IsBin) { |
| 7633 | if (LHSKind == NullabilityKind::NonNull) |
| 7634 | MergedKind = NullabilityKind::NonNull; |
| 7635 | else |
| 7636 | MergedKind = RHSKind; |
| 7637 | // Compute nullability of a normal conditional expression. |
| 7638 | } else { |
| 7639 | if (LHSKind == NullabilityKind::Nullable || |
| 7640 | RHSKind == NullabilityKind::Nullable) |
| 7641 | MergedKind = NullabilityKind::Nullable; |
| 7642 | else if (LHSKind == NullabilityKind::NonNull) |
| 7643 | MergedKind = RHSKind; |
| 7644 | else if (RHSKind == NullabilityKind::NonNull) |
| 7645 | MergedKind = LHSKind; |
| 7646 | else |
| 7647 | MergedKind = NullabilityKind::Unspecified; |
| 7648 | } |
| 7649 | |
| 7650 | // Return if ResTy already has the correct nullability. |
| 7651 | if (GetNullability(ResTy) == MergedKind) |
| 7652 | return ResTy; |
| 7653 | |
| 7654 | // Strip all nullability from ResTy. |
| 7655 | while (ResTy->getNullability(Ctx)) |
| 7656 | ResTy = ResTy.getSingleStepDesugaredType(Ctx); |
| 7657 | |
| 7658 | // Create a new AttributedType with the new nullability kind. |
| 7659 | auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); |
| 7660 | return Ctx.getAttributedType(NewAttr, ResTy, ResTy); |
| 7661 | } |
| 7662 | |
| 7663 | /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null |
| 7664 | /// in the case of a the GNU conditional expr extension. |
| 7665 | ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, |
| 7666 | SourceLocation ColonLoc, |
| 7667 | Expr *CondExpr, Expr *LHSExpr, |
| 7668 | Expr *RHSExpr) { |
| 7669 | if (!getLangOpts().CPlusPlus) { |
| 7670 | // C cannot handle TypoExpr nodes in the condition because it |
| 7671 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
| 7672 | // been dealt with before checking the operands. |
| 7673 | ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); |
| 7674 | ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); |
| 7675 | ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); |
| 7676 | |
| 7677 | if (!CondResult.isUsable()) |
| 7678 | return ExprError(); |
| 7679 | |
| 7680 | if (LHSExpr) { |
| 7681 | if (!LHSResult.isUsable()) |
| 7682 | return ExprError(); |
| 7683 | } |
| 7684 | |
| 7685 | if (!RHSResult.isUsable()) |
| 7686 | return ExprError(); |
| 7687 | |
| 7688 | CondExpr = CondResult.get(); |
| 7689 | LHSExpr = LHSResult.get(); |
| 7690 | RHSExpr = RHSResult.get(); |
| 7691 | } |
| 7692 | |
| 7693 | // If this is the gnu "x ?: y" extension, analyze the types as though the LHS |
| 7694 | // was the condition. |
| 7695 | OpaqueValueExpr *opaqueValue = nullptr; |
| 7696 | Expr *commonExpr = nullptr; |
| 7697 | if (!LHSExpr) { |
| 7698 | commonExpr = CondExpr; |
| 7699 | // Lower out placeholder types first. This is important so that we don't |
| 7700 | // try to capture a placeholder. This happens in few cases in C++; such |
| 7701 | // as Objective-C++'s dictionary subscripting syntax. |
| 7702 | if (commonExpr->hasPlaceholderType()) { |
| 7703 | ExprResult result = CheckPlaceholderExpr(commonExpr); |
| 7704 | if (!result.isUsable()) return ExprError(); |
| 7705 | commonExpr = result.get(); |
| 7706 | } |
| 7707 | // We usually want to apply unary conversions *before* saving, except |
| 7708 | // in the special case of a C++ l-value conditional. |
| 7709 | if (!(getLangOpts().CPlusPlus |
| 7710 | && !commonExpr->isTypeDependent() |
| 7711 | && commonExpr->getValueKind() == RHSExpr->getValueKind() |
| 7712 | && commonExpr->isGLValue() |
| 7713 | && commonExpr->isOrdinaryOrBitFieldObject() |
| 7714 | && RHSExpr->isOrdinaryOrBitFieldObject() |
| 7715 | && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { |
| 7716 | ExprResult commonRes = UsualUnaryConversions(commonExpr); |
| 7717 | if (commonRes.isInvalid()) |
| 7718 | return ExprError(); |
| 7719 | commonExpr = commonRes.get(); |
| 7720 | } |
| 7721 | |
| 7722 | // If the common expression is a class or array prvalue, materialize it |
| 7723 | // so that we can safely refer to it multiple times. |
| 7724 | if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || |
| 7725 | commonExpr->getType()->isArrayType())) { |
| 7726 | ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); |
| 7727 | if (MatExpr.isInvalid()) |
| 7728 | return ExprError(); |
| 7729 | commonExpr = MatExpr.get(); |
| 7730 | } |
| 7731 | |
| 7732 | opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), |
| 7733 | commonExpr->getType(), |
| 7734 | commonExpr->getValueKind(), |
| 7735 | commonExpr->getObjectKind(), |
| 7736 | commonExpr); |
| 7737 | LHSExpr = CondExpr = opaqueValue; |
| 7738 | } |
| 7739 | |
| 7740 | QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); |
| 7741 | ExprValueKind VK = VK_RValue; |
| 7742 | ExprObjectKind OK = OK_Ordinary; |
| 7743 | ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; |
| 7744 | QualType result = CheckConditionalOperands(Cond, LHS, RHS, |
| 7745 | VK, OK, QuestionLoc); |
| 7746 | if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || |
| 7747 | RHS.isInvalid()) |
| 7748 | return ExprError(); |
| 7749 | |
| 7750 | DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), |
| 7751 | RHS.get()); |
| 7752 | |
| 7753 | CheckBoolLikeConversion(Cond.get(), QuestionLoc); |
| 7754 | |
| 7755 | result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, |
| 7756 | Context); |
| 7757 | |
| 7758 | if (!commonExpr) |
| 7759 | return new (Context) |
| 7760 | ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, |
| 7761 | RHS.get(), result, VK, OK); |
| 7762 | |
| 7763 | return new (Context) BinaryConditionalOperator( |
| 7764 | commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, |
| 7765 | ColonLoc, result, VK, OK); |
| 7766 | } |
| 7767 | |
| 7768 | // checkPointerTypesForAssignment - This is a very tricky routine (despite |
| 7769 | // being closely modeled after the C99 spec:-). The odd characteristic of this |
| 7770 | // routine is it effectively iqnores the qualifiers on the top level pointee. |
| 7771 | // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. |
| 7772 | // FIXME: add a couple examples in this comment. |
| 7773 | static Sema::AssignConvertType |
| 7774 | checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { |
| 7775 | assert(LHSType.isCanonical() && "LHS not canonicalized!" ); |
| 7776 | assert(RHSType.isCanonical() && "RHS not canonicalized!" ); |
| 7777 | |
| 7778 | // get the "pointed to" type (ignoring qualifiers at the top level) |
| 7779 | const Type *lhptee, *rhptee; |
| 7780 | Qualifiers lhq, rhq; |
| 7781 | std::tie(lhptee, lhq) = |
| 7782 | cast<PointerType>(LHSType)->getPointeeType().split().asPair(); |
| 7783 | std::tie(rhptee, rhq) = |
| 7784 | cast<PointerType>(RHSType)->getPointeeType().split().asPair(); |
| 7785 | |
| 7786 | Sema::AssignConvertType ConvTy = Sema::Compatible; |
| 7787 | |
| 7788 | // C99 6.5.16.1p1: This following citation is common to constraints |
| 7789 | // 3 & 4 (below). ...and the type *pointed to* by the left has all the |
| 7790 | // qualifiers of the type *pointed to* by the right; |
| 7791 | |
| 7792 | // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. |
| 7793 | if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && |
| 7794 | lhq.compatiblyIncludesObjCLifetime(rhq)) { |
| 7795 | // Ignore lifetime for further calculation. |
| 7796 | lhq.removeObjCLifetime(); |
| 7797 | rhq.removeObjCLifetime(); |
| 7798 | } |
| 7799 | |
| 7800 | if (!lhq.compatiblyIncludes(rhq)) { |
| 7801 | // Treat address-space mismatches as fatal. |
| 7802 | if (!lhq.isAddressSpaceSupersetOf(rhq)) |
| 7803 | return Sema::IncompatiblePointerDiscardsQualifiers; |
| 7804 | |
| 7805 | // It's okay to add or remove GC or lifetime qualifiers when converting to |
| 7806 | // and from void*. |
| 7807 | else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() |
| 7808 | .compatiblyIncludes( |
| 7809 | rhq.withoutObjCGCAttr().withoutObjCLifetime()) |
| 7810 | && (lhptee->isVoidType() || rhptee->isVoidType())) |
| 7811 | ; // keep old |
| 7812 | |
| 7813 | // Treat lifetime mismatches as fatal. |
| 7814 | else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) |
| 7815 | ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; |
| 7816 | |
| 7817 | // For GCC/MS compatibility, other qualifier mismatches are treated |
| 7818 | // as still compatible in C. |
| 7819 | else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; |
| 7820 | } |
| 7821 | |
| 7822 | // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or |
| 7823 | // incomplete type and the other is a pointer to a qualified or unqualified |
| 7824 | // version of void... |
| 7825 | if (lhptee->isVoidType()) { |
| 7826 | if (rhptee->isIncompleteOrObjectType()) |
| 7827 | return ConvTy; |
| 7828 | |
| 7829 | // As an extension, we allow cast to/from void* to function pointer. |
| 7830 | assert(rhptee->isFunctionType()); |
| 7831 | return Sema::FunctionVoidPointer; |
| 7832 | } |
| 7833 | |
| 7834 | if (rhptee->isVoidType()) { |
| 7835 | if (lhptee->isIncompleteOrObjectType()) |
| 7836 | return ConvTy; |
| 7837 | |
| 7838 | // As an extension, we allow cast to/from void* to function pointer. |
| 7839 | assert(lhptee->isFunctionType()); |
| 7840 | return Sema::FunctionVoidPointer; |
| 7841 | } |
| 7842 | |
| 7843 | // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or |
| 7844 | // unqualified versions of compatible types, ... |
| 7845 | QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); |
| 7846 | if (!S.Context.typesAreCompatible(ltrans, rtrans)) { |
| 7847 | // Check if the pointee types are compatible ignoring the sign. |
| 7848 | // We explicitly check for char so that we catch "char" vs |
| 7849 | // "unsigned char" on systems where "char" is unsigned. |
| 7850 | if (lhptee->isCharType()) |
| 7851 | ltrans = S.Context.UnsignedCharTy; |
| 7852 | else if (lhptee->hasSignedIntegerRepresentation()) |
| 7853 | ltrans = S.Context.getCorrespondingUnsignedType(ltrans); |
| 7854 | |
| 7855 | if (rhptee->isCharType()) |
| 7856 | rtrans = S.Context.UnsignedCharTy; |
| 7857 | else if (rhptee->hasSignedIntegerRepresentation()) |
| 7858 | rtrans = S.Context.getCorrespondingUnsignedType(rtrans); |
| 7859 | |
| 7860 | if (ltrans == rtrans) { |
| 7861 | // Types are compatible ignoring the sign. Qualifier incompatibility |
| 7862 | // takes priority over sign incompatibility because the sign |
| 7863 | // warning can be disabled. |
| 7864 | if (ConvTy != Sema::Compatible) |
| 7865 | return ConvTy; |
| 7866 | |
| 7867 | return Sema::IncompatiblePointerSign; |
| 7868 | } |
| 7869 | |
| 7870 | // If we are a multi-level pointer, it's possible that our issue is simply |
| 7871 | // one of qualification - e.g. char ** -> const char ** is not allowed. If |
| 7872 | // the eventual target type is the same and the pointers have the same |
| 7873 | // level of indirection, this must be the issue. |
| 7874 | if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { |
| 7875 | do { |
| 7876 | std::tie(lhptee, lhq) = |
| 7877 | cast<PointerType>(lhptee)->getPointeeType().split().asPair(); |
| 7878 | std::tie(rhptee, rhq) = |
| 7879 | cast<PointerType>(rhptee)->getPointeeType().split().asPair(); |
| 7880 | |
| 7881 | // Inconsistent address spaces at this point is invalid, even if the |
| 7882 | // address spaces would be compatible. |
| 7883 | // FIXME: This doesn't catch address space mismatches for pointers of |
| 7884 | // different nesting levels, like: |
| 7885 | // __local int *** a; |
| 7886 | // int ** b = a; |
| 7887 | // It's not clear how to actually determine when such pointers are |
| 7888 | // invalidly incompatible. |
| 7889 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) |
| 7890 | return Sema::IncompatibleNestedPointerAddressSpaceMismatch; |
| 7891 | |
| 7892 | } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); |
| 7893 | |
| 7894 | if (lhptee == rhptee) |
| 7895 | return Sema::IncompatibleNestedPointerQualifiers; |
| 7896 | } |
| 7897 | |
| 7898 | // General pointer incompatibility takes priority over qualifiers. |
| 7899 | return Sema::IncompatiblePointer; |
| 7900 | } |
| 7901 | if (!S.getLangOpts().CPlusPlus && |
| 7902 | S.IsFunctionConversion(ltrans, rtrans, ltrans)) |
| 7903 | return Sema::IncompatiblePointer; |
| 7904 | return ConvTy; |
| 7905 | } |
| 7906 | |
| 7907 | /// checkBlockPointerTypesForAssignment - This routine determines whether two |
| 7908 | /// block pointer types are compatible or whether a block and normal pointer |
| 7909 | /// are compatible. It is more restrict than comparing two function pointer |
| 7910 | // types. |
| 7911 | static Sema::AssignConvertType |
| 7912 | checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, |
| 7913 | QualType RHSType) { |
| 7914 | assert(LHSType.isCanonical() && "LHS not canonicalized!" ); |
| 7915 | assert(RHSType.isCanonical() && "RHS not canonicalized!" ); |
| 7916 | |
| 7917 | QualType lhptee, rhptee; |
| 7918 | |
| 7919 | // get the "pointed to" type (ignoring qualifiers at the top level) |
| 7920 | lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); |
| 7921 | rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); |
| 7922 | |
| 7923 | // In C++, the types have to match exactly. |
| 7924 | if (S.getLangOpts().CPlusPlus) |
| 7925 | return Sema::IncompatibleBlockPointer; |
| 7926 | |
| 7927 | Sema::AssignConvertType ConvTy = Sema::Compatible; |
| 7928 | |
| 7929 | // For blocks we enforce that qualifiers are identical. |
| 7930 | Qualifiers LQuals = lhptee.getLocalQualifiers(); |
| 7931 | Qualifiers RQuals = rhptee.getLocalQualifiers(); |
| 7932 | if (S.getLangOpts().OpenCL) { |
| 7933 | LQuals.removeAddressSpace(); |
| 7934 | RQuals.removeAddressSpace(); |
| 7935 | } |
| 7936 | if (LQuals != RQuals) |
| 7937 | ConvTy = Sema::CompatiblePointerDiscardsQualifiers; |
| 7938 | |
| 7939 | // FIXME: OpenCL doesn't define the exact compile time semantics for a block |
| 7940 | // assignment. |
| 7941 | // The current behavior is similar to C++ lambdas. A block might be |
| 7942 | // assigned to a variable iff its return type and parameters are compatible |
| 7943 | // (C99 6.2.7) with the corresponding return type and parameters of the LHS of |
| 7944 | // an assignment. Presumably it should behave in way that a function pointer |
| 7945 | // assignment does in C, so for each parameter and return type: |
| 7946 | // * CVR and address space of LHS should be a superset of CVR and address |
| 7947 | // space of RHS. |
| 7948 | // * unqualified types should be compatible. |
| 7949 | if (S.getLangOpts().OpenCL) { |
| 7950 | if (!S.Context.typesAreBlockPointerCompatible( |
| 7951 | S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), |
| 7952 | S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) |
| 7953 | return Sema::IncompatibleBlockPointer; |
| 7954 | } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) |
| 7955 | return Sema::IncompatibleBlockPointer; |
| 7956 | |
| 7957 | return ConvTy; |
| 7958 | } |
| 7959 | |
| 7960 | /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types |
| 7961 | /// for assignment compatibility. |
| 7962 | static Sema::AssignConvertType |
| 7963 | checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, |
| 7964 | QualType RHSType) { |
| 7965 | assert(LHSType.isCanonical() && "LHS was not canonicalized!" ); |
| 7966 | assert(RHSType.isCanonical() && "RHS was not canonicalized!" ); |
| 7967 | |
| 7968 | if (LHSType->isObjCBuiltinType()) { |
| 7969 | // Class is not compatible with ObjC object pointers. |
| 7970 | if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && |
| 7971 | !RHSType->isObjCQualifiedClassType()) |
| 7972 | return Sema::IncompatiblePointer; |
| 7973 | return Sema::Compatible; |
| 7974 | } |
| 7975 | if (RHSType->isObjCBuiltinType()) { |
| 7976 | if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && |
| 7977 | !LHSType->isObjCQualifiedClassType()) |
| 7978 | return Sema::IncompatiblePointer; |
| 7979 | return Sema::Compatible; |
| 7980 | } |
| 7981 | QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); |
| 7982 | QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); |
| 7983 | |
| 7984 | if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && |
| 7985 | // make an exception for id<P> |
| 7986 | !LHSType->isObjCQualifiedIdType()) |
| 7987 | return Sema::CompatiblePointerDiscardsQualifiers; |
| 7988 | |
| 7989 | if (S.Context.typesAreCompatible(LHSType, RHSType)) |
| 7990 | return Sema::Compatible; |
| 7991 | if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) |
| 7992 | return Sema::IncompatibleObjCQualifiedId; |
| 7993 | return Sema::IncompatiblePointer; |
| 7994 | } |
| 7995 | |
| 7996 | Sema::AssignConvertType |
| 7997 | Sema::CheckAssignmentConstraints(SourceLocation Loc, |
| 7998 | QualType LHSType, QualType RHSType) { |
| 7999 | // Fake up an opaque expression. We don't actually care about what |
| 8000 | // cast operations are required, so if CheckAssignmentConstraints |
| 8001 | // adds casts to this they'll be wasted, but fortunately that doesn't |
| 8002 | // usually happen on valid code. |
| 8003 | OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); |
| 8004 | ExprResult RHSPtr = &RHSExpr; |
| 8005 | CastKind K; |
| 8006 | |
| 8007 | return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); |
| 8008 | } |
| 8009 | |
| 8010 | /// This helper function returns true if QT is a vector type that has element |
| 8011 | /// type ElementType. |
| 8012 | static bool isVector(QualType QT, QualType ElementType) { |
| 8013 | if (const VectorType *VT = QT->getAs<VectorType>()) |
| 8014 | return VT->getElementType() == ElementType; |
| 8015 | return false; |
| 8016 | } |
| 8017 | |
| 8018 | /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently |
| 8019 | /// has code to accommodate several GCC extensions when type checking |
| 8020 | /// pointers. Here are some objectionable examples that GCC considers warnings: |
| 8021 | /// |
| 8022 | /// int a, *pint; |
| 8023 | /// short *pshort; |
| 8024 | /// struct foo *pfoo; |
| 8025 | /// |
| 8026 | /// pint = pshort; // warning: assignment from incompatible pointer type |
| 8027 | /// a = pint; // warning: assignment makes integer from pointer without a cast |
| 8028 | /// pint = a; // warning: assignment makes pointer from integer without a cast |
| 8029 | /// pint = pfoo; // warning: assignment from incompatible pointer type |
| 8030 | /// |
| 8031 | /// As a result, the code for dealing with pointers is more complex than the |
| 8032 | /// C99 spec dictates. |
| 8033 | /// |
| 8034 | /// Sets 'Kind' for any result kind except Incompatible. |
| 8035 | Sema::AssignConvertType |
| 8036 | Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, |
| 8037 | CastKind &Kind, bool ConvertRHS) { |
| 8038 | QualType RHSType = RHS.get()->getType(); |
| 8039 | QualType OrigLHSType = LHSType; |
| 8040 | QualType OrigRHSType = RHSType; |
| 8041 | |
| 8042 | // Get canonical types. We're not formatting these types, just comparing |
| 8043 | // them. |
| 8044 | LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); |
| 8045 | RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); |
| 8046 | |
| 8047 | // Common case: no conversion required. |
| 8048 | if (LHSType == RHSType) { |
| 8049 | Kind = CK_NoOp; |
| 8050 | return Compatible; |
| 8051 | } |
| 8052 | |
| 8053 | // If we have an atomic type, try a non-atomic assignment, then just add an |
| 8054 | // atomic qualification step. |
| 8055 | if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { |
| 8056 | Sema::AssignConvertType result = |
| 8057 | CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); |
| 8058 | if (result != Compatible) |
| 8059 | return result; |
| 8060 | if (Kind != CK_NoOp && ConvertRHS) |
| 8061 | RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); |
| 8062 | Kind = CK_NonAtomicToAtomic; |
| 8063 | return Compatible; |
| 8064 | } |
| 8065 | |
| 8066 | // If the left-hand side is a reference type, then we are in a |
| 8067 | // (rare!) case where we've allowed the use of references in C, |
| 8068 | // e.g., as a parameter type in a built-in function. In this case, |
| 8069 | // just make sure that the type referenced is compatible with the |
| 8070 | // right-hand side type. The caller is responsible for adjusting |
| 8071 | // LHSType so that the resulting expression does not have reference |
| 8072 | // type. |
| 8073 | if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { |
| 8074 | if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { |
| 8075 | Kind = CK_LValueBitCast; |
| 8076 | return Compatible; |
| 8077 | } |
| 8078 | return Incompatible; |
| 8079 | } |
| 8080 | |
| 8081 | // Allow scalar to ExtVector assignments, and assignments of an ExtVector type |
| 8082 | // to the same ExtVector type. |
| 8083 | if (LHSType->isExtVectorType()) { |
| 8084 | if (RHSType->isExtVectorType()) |
| 8085 | return Incompatible; |
| 8086 | if (RHSType->isArithmeticType()) { |
| 8087 | // CK_VectorSplat does T -> vector T, so first cast to the element type. |
| 8088 | if (ConvertRHS) |
| 8089 | RHS = prepareVectorSplat(LHSType, RHS.get()); |
| 8090 | Kind = CK_VectorSplat; |
| 8091 | return Compatible; |
| 8092 | } |
| 8093 | } |
| 8094 | |
| 8095 | // Conversions to or from vector type. |
| 8096 | if (LHSType->isVectorType() || RHSType->isVectorType()) { |
| 8097 | if (LHSType->isVectorType() && RHSType->isVectorType()) { |
| 8098 | // Allow assignments of an AltiVec vector type to an equivalent GCC |
| 8099 | // vector type and vice versa |
| 8100 | if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { |
| 8101 | Kind = CK_BitCast; |
| 8102 | return Compatible; |
| 8103 | } |
| 8104 | |
| 8105 | // If we are allowing lax vector conversions, and LHS and RHS are both |
| 8106 | // vectors, the total size only needs to be the same. This is a bitcast; |
| 8107 | // no bits are changed but the result type is different. |
| 8108 | if (isLaxVectorConversion(RHSType, LHSType)) { |
| 8109 | Kind = CK_BitCast; |
| 8110 | return IncompatibleVectors; |
| 8111 | } |
| 8112 | } |
| 8113 | |
| 8114 | // When the RHS comes from another lax conversion (e.g. binops between |
| 8115 | // scalars and vectors) the result is canonicalized as a vector. When the |
| 8116 | // LHS is also a vector, the lax is allowed by the condition above. Handle |
| 8117 | // the case where LHS is a scalar. |
| 8118 | if (LHSType->isScalarType()) { |
| 8119 | const VectorType *VecType = RHSType->getAs<VectorType>(); |
| 8120 | if (VecType && VecType->getNumElements() == 1 && |
| 8121 | isLaxVectorConversion(RHSType, LHSType)) { |
| 8122 | ExprResult *VecExpr = &RHS; |
| 8123 | *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); |
| 8124 | Kind = CK_BitCast; |
| 8125 | return Compatible; |
| 8126 | } |
| 8127 | } |
| 8128 | |
| 8129 | return Incompatible; |
| 8130 | } |
| 8131 | |
| 8132 | // Diagnose attempts to convert between __float128 and long double where |
| 8133 | // such conversions currently can't be handled. |
| 8134 | if (unsupportedTypeConversion(*this, LHSType, RHSType)) |
| 8135 | return Incompatible; |
| 8136 | |
| 8137 | // Disallow assigning a _Complex to a real type in C++ mode since it simply |
| 8138 | // discards the imaginary part. |
| 8139 | if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && |
| 8140 | !LHSType->getAs<ComplexType>()) |
| 8141 | return Incompatible; |
| 8142 | |
| 8143 | // Arithmetic conversions. |
| 8144 | if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && |
| 8145 | !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { |
| 8146 | if (ConvertRHS) |
| 8147 | Kind = PrepareScalarCast(RHS, LHSType); |
| 8148 | return Compatible; |
| 8149 | } |
| 8150 | |
| 8151 | // CHERI callbacks may only be cast to other cheri callback types |
| 8152 | bool RHSIsCallback = false; |
| 8153 | bool LHSIsCallback = false; |
| 8154 | if (auto RHSPointer = dyn_cast<PointerType>(RHSType)) |
| 8155 | if (auto RHSFnPTy = RHSPointer->getPointeeType()->getAs<FunctionType>()) |
| 8156 | if (RHSFnPTy->getCallConv() == CC_CHERICCallback) |
| 8157 | RHSIsCallback = true; |
| 8158 | if (auto LHSPointer = dyn_cast<PointerType>(LHSType)) |
| 8159 | if (auto LHSFnPTy = LHSPointer->getPointeeType()->getAs<FunctionType>()) |
| 8160 | if (LHSFnPTy->getCallConv() == CC_CHERICCallback) |
| 8161 | LHSIsCallback = true; |
| 8162 | if (RHSIsCallback != LHSIsCallback) |
| 8163 | return Incompatible; |
| 8164 | |
| 8165 | // Conversions to normal pointers. |
| 8166 | if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { |
| 8167 | // U* -> T* |
| 8168 | if (const PointerType *RHSPointer = dyn_cast<PointerType>(RHSType)) { |
| 8169 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
| 8170 | LangAS AddrSpaceR = RHSPointer->getPointeeType().getAddressSpace(); |
| 8171 | if (AddrSpaceL != AddrSpaceR) |
| 8172 | Kind = CK_AddressSpaceConversion; |
| 8173 | else if (LHSPointer->isFunctionPointerType() && RHSPointer->isFunctionPointerType()) { |
| 8174 | // only allow implicit casts to and from function pointer capabilities |
| 8175 | if (!LHSPointer->isCHERICapability() && RHSPointer->isCHERICapability()) |
| 8176 | Kind = CK_CHERICapabilityToPointer; |
| 8177 | else if (LHSPointer->isCHERICapability() && !RHSPointer->isCHERICapability()) |
| 8178 | Kind = CK_PointerToCHERICapability; |
| 8179 | else |
| 8180 | Kind = CK_BitCast; |
| 8181 | } else if (LHSPointer->isCHERICapability() != RHSPointer->isCHERICapability()) { |
| 8182 | // all other implicit casts to and from capabilities are not allowed |
| 8183 | Kind = RHSPointer->isCHERICapability() ? CK_CHERICapabilityToPointer : |
| 8184 | CK_PointerToCHERICapability; |
| 8185 | return RHSPointer->isCHERICapability() ? CHERICapabilityToPointer : |
| 8186 | PointerToCHERICapability; |
| 8187 | } else { |
| 8188 | if (Context.hasCvrSimilarType(RHSType, LHSType)) |
| 8189 | Kind = CK_NoOp; |
| 8190 | else |
| 8191 | Kind = CK_BitCast; |
| 8192 | if (RHSPointer->isCHERICapability() && isa<PointerType>(OrigRHSType) && |
| 8193 | RHSPointer->getPointeeType()->isVoidType()) |
| 8194 | if (auto *TT = dyn_cast<TypedefType>( |
| 8195 | cast<PointerType>(OrigRHSType)->getPointeeType())) { |
| 8196 | unsigned FromAlign = Context.getTypeAlignInChars(TT).getQuantity(); |
| 8197 | unsigned ToAlign = |
| 8198 | Context.getTypeAlignInChars(LHSType).getQuantity(); |
| 8199 | if ((FromAlign > 1) && (ToAlign > FromAlign)) |
| 8200 | Diag(RHS.get()->getExprLoc(), diag::err_cheri_ptr_align) << |
| 8201 | OrigRHSType << LHSType << FromAlign << ToAlign; |
| 8202 | } |
| 8203 | } |
| 8204 | return checkPointerTypesForAssignment(*this, LHSType, RHSType); |
| 8205 | } |
| 8206 | |
| 8207 | // int -> T* |
| 8208 | if (RHSType->isIntegerType()) { |
| 8209 | // Implicit casts from int -> memory capabilities are not allowed (except for null) |
| 8210 | const Expr::NullPointerConstantKind RHSNullKind = |
| 8211 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); |
| 8212 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
| 8213 | if (LHSPointer->isCHERICapability() && !RHSIsNull && |
| 8214 | !RHSType->isIntCapType()) |
| 8215 | return Incompatible; |
| 8216 | Kind = CK_IntegralToPointer; // FIXME: null? |
| 8217 | return IntToPointer; |
| 8218 | } |
| 8219 | |
| 8220 | // C pointers are not compatible with ObjC object pointers, |
| 8221 | // with two exceptions: |
| 8222 | if (isa<ObjCObjectPointerType>(RHSType)) { |
| 8223 | // - conversions to void* |
| 8224 | if (LHSPointer->getPointeeType()->isVoidType()) { |
| 8225 | Kind = CK_BitCast; |
| 8226 | return Compatible; |
| 8227 | } |
| 8228 | |
| 8229 | // - conversions from 'Class' to the redefinition type |
| 8230 | if (RHSType->isObjCClassType() && |
| 8231 | Context.hasSameType(LHSType, |
| 8232 | Context.getObjCClassRedefinitionType())) { |
| 8233 | Kind = CK_BitCast; |
| 8234 | return Compatible; |
| 8235 | } |
| 8236 | |
| 8237 | Kind = CK_BitCast; |
| 8238 | return IncompatiblePointer; |
| 8239 | } |
| 8240 | |
| 8241 | // U^ -> void* |
| 8242 | if (RHSType->getAs<BlockPointerType>()) { |
| 8243 | if (LHSPointer->getPointeeType()->isVoidType()) { |
| 8244 | LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); |
| 8245 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
| 8246 | ->getPointeeType() |
| 8247 | .getAddressSpace(); |
| 8248 | Kind = |
| 8249 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
| 8250 | return Compatible; |
| 8251 | } |
| 8252 | } |
| 8253 | |
| 8254 | return Incompatible; |
| 8255 | } |
| 8256 | |
| 8257 | // Conversions to block pointers. |
| 8258 | if (isa<BlockPointerType>(LHSType)) { |
| 8259 | // U^ -> T^ |
| 8260 | if (RHSType->isBlockPointerType()) { |
| 8261 | LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() |
| 8262 | ->getPointeeType() |
| 8263 | .getAddressSpace(); |
| 8264 | LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() |
| 8265 | ->getPointeeType() |
| 8266 | .getAddressSpace(); |
| 8267 | Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
| 8268 | return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); |
| 8269 | } |
| 8270 | |
| 8271 | // int or null -> T^ |
| 8272 | if (RHSType->isIntegerType()) { |
| 8273 | Kind = CK_IntegralToPointer; // FIXME: null |
| 8274 | return IntToBlockPointer; |
| 8275 | } |
| 8276 | |
| 8277 | // id -> T^ |
| 8278 | if (getLangOpts().ObjC && RHSType->isObjCIdType()) { |
| 8279 | Kind = CK_AnyPointerToBlockPointerCast; |
| 8280 | return Compatible; |
| 8281 | } |
| 8282 | |
| 8283 | // void* -> T^ |
| 8284 | if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) |
| 8285 | if (RHSPT->getPointeeType()->isVoidType()) { |
| 8286 | Kind = CK_AnyPointerToBlockPointerCast; |
| 8287 | return Compatible; |
| 8288 | } |
| 8289 | |
| 8290 | return Incompatible; |
| 8291 | } |
| 8292 | |
| 8293 | // Conversions to Objective-C pointers. |
| 8294 | if (isa<ObjCObjectPointerType>(LHSType)) { |
| 8295 | // A* -> B* |
| 8296 | if (RHSType->isObjCObjectPointerType()) { |
| 8297 | Kind = CK_BitCast; |
| 8298 | Sema::AssignConvertType result = |
| 8299 | checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); |
| 8300 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 8301 | result == Compatible && |
| 8302 | !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) |
| 8303 | result = IncompatibleObjCWeakRef; |
| 8304 | return result; |
| 8305 | } |
| 8306 | |
| 8307 | // int or null -> A* |
| 8308 | if (RHSType->isIntegerType()) { |
| 8309 | Kind = CK_IntegralToPointer; // FIXME: null |
| 8310 | return IntToPointer; |
| 8311 | } |
| 8312 | |
| 8313 | // In general, C pointers are not compatible with ObjC object pointers, |
| 8314 | // with two exceptions: |
| 8315 | if (isa<PointerType>(RHSType)) { |
| 8316 | Kind = CK_CPointerToObjCPointerCast; |
| 8317 | |
| 8318 | // - conversions from 'void*' |
| 8319 | if (RHSType->isVoidPointerType()) { |
| 8320 | return Compatible; |
| 8321 | } |
| 8322 | |
| 8323 | // - conversions to 'Class' from its redefinition type |
| 8324 | if (LHSType->isObjCClassType() && |
| 8325 | Context.hasSameType(RHSType, |
| 8326 | Context.getObjCClassRedefinitionType())) { |
| 8327 | return Compatible; |
| 8328 | } |
| 8329 | |
| 8330 | return IncompatiblePointer; |
| 8331 | } |
| 8332 | |
| 8333 | // Only under strict condition T^ is compatible with an Objective-C pointer. |
| 8334 | if (RHSType->isBlockPointerType() && |
| 8335 | LHSType->isBlockCompatibleObjCPointerType(Context)) { |
| 8336 | if (ConvertRHS) |
| 8337 | maybeExtendBlockObject(RHS); |
| 8338 | Kind = CK_BlockPointerToObjCPointerCast; |
| 8339 | return Compatible; |
| 8340 | } |
| 8341 | |
| 8342 | return Incompatible; |
| 8343 | } |
| 8344 | |
| 8345 | // Conversions from pointers that are not covered by the above. |
| 8346 | if (const PointerType *RHSPointer = dyn_cast<PointerType>(RHSType)) { |
| 8347 | // T* -> _Bool |
| 8348 | if (LHSType == Context.BoolTy) { |
| 8349 | Kind = CK_PointerToBoolean; |
| 8350 | return Compatible; |
| 8351 | } |
| 8352 | |
| 8353 | // T* -> int |
| 8354 | if (LHSType->isIntegerType()) { |
| 8355 | // Implicit casts from memory capabilities -> int are not allowed (except for null) |
| 8356 | const Expr::NullPointerConstantKind RHSNullKind = |
| 8357 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); |
| 8358 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
| 8359 | if (RHSPointer->isCHERICapability() && !RHSIsNull && |
| 8360 | !LHSType->isIntCapType()) |
| 8361 | return Incompatible; |
| 8362 | Kind = CK_PointerToIntegral; |
| 8363 | return PointerToInt; |
| 8364 | } |
| 8365 | |
| 8366 | return Incompatible; |
| 8367 | } |
| 8368 | |
| 8369 | // Conversions from Objective-C pointers that are not covered by the above. |
| 8370 | if (isa<ObjCObjectPointerType>(RHSType)) { |
| 8371 | // T* -> _Bool |
| 8372 | if (LHSType == Context.BoolTy) { |
| 8373 | Kind = CK_PointerToBoolean; |
| 8374 | return Compatible; |
| 8375 | } |
| 8376 | |
| 8377 | // T* -> int |
| 8378 | if (LHSType->isIntegerType()) { |
| 8379 | Kind = CK_PointerToIntegral; |
| 8380 | return PointerToInt; |
| 8381 | } |
| 8382 | |
| 8383 | return Incompatible; |
| 8384 | } |
| 8385 | |
| 8386 | // struct A -> struct B |
| 8387 | if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { |
| 8388 | if (Context.typesAreCompatible(LHSType, RHSType)) { |
| 8389 | Kind = CK_NoOp; |
| 8390 | return Compatible; |
| 8391 | } |
| 8392 | } |
| 8393 | |
| 8394 | if (LHSType->isSamplerT() && RHSType->isIntegerType()) { |
| 8395 | Kind = CK_IntToOCLSampler; |
| 8396 | return Compatible; |
| 8397 | } |
| 8398 | |
| 8399 | return Incompatible; |
| 8400 | } |
| 8401 | |
| 8402 | /// Constructs a transparent union from an expression that is |
| 8403 | /// used to initialize the transparent union. |
| 8404 | static void ConstructTransparentUnion(Sema &S, ASTContext &C, |
| 8405 | ExprResult &EResult, QualType UnionType, |
| 8406 | FieldDecl *Field) { |
| 8407 | // Build an initializer list that designates the appropriate member |
| 8408 | // of the transparent union. |
| 8409 | Expr *E = EResult.get(); |
| 8410 | InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), |
| 8411 | E, SourceLocation()); |
| 8412 | Initializer->setType(UnionType); |
| 8413 | Initializer->setInitializedFieldInUnion(Field); |
| 8414 | |
| 8415 | // Build a compound literal constructing a value of the transparent |
| 8416 | // union type from this initializer list. |
| 8417 | TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); |
| 8418 | EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, |
| 8419 | VK_RValue, Initializer, false); |
| 8420 | } |
| 8421 | |
| 8422 | Sema::AssignConvertType |
| 8423 | Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, |
| 8424 | ExprResult &RHS) { |
| 8425 | QualType RHSType = RHS.get()->getType(); |
| 8426 | |
| 8427 | // If the ArgType is a Union type, we want to handle a potential |
| 8428 | // transparent_union GCC extension. |
| 8429 | const RecordType *UT = ArgType->getAsUnionType(); |
| 8430 | if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) |
| 8431 | return Incompatible; |
| 8432 | |
| 8433 | // The field to initialize within the transparent union. |
| 8434 | RecordDecl *UD = UT->getDecl(); |
| 8435 | FieldDecl *InitField = nullptr; |
| 8436 | // It's compatible if the expression matches any of the fields. |
| 8437 | for (auto *it : UD->fields()) { |
| 8438 | if (it->getType()->isPointerType()) { |
| 8439 | // If the transparent union contains a pointer type, we allow: |
| 8440 | // 1) void pointer |
| 8441 | // 2) null pointer constant |
| 8442 | if (RHSType->isPointerType()) |
| 8443 | if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { |
| 8444 | RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); |
| 8445 | InitField = it; |
| 8446 | break; |
| 8447 | } |
| 8448 | |
| 8449 | if (RHS.get()->isNullPointerConstant(Context, |
| 8450 | Expr::NPC_ValueDependentIsNull)) { |
| 8451 | RHS = ImpCastExprToType(RHS.get(), it->getType(), |
| 8452 | CK_NullToPointer); |
| 8453 | InitField = it; |
| 8454 | break; |
| 8455 | } |
| 8456 | } |
| 8457 | |
| 8458 | CastKind Kind; |
| 8459 | if (CheckAssignmentConstraints(it->getType(), RHS, Kind) |
| 8460 | == Compatible) { |
| 8461 | RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); |
| 8462 | InitField = it; |
| 8463 | break; |
| 8464 | } |
| 8465 | } |
| 8466 | |
| 8467 | if (!InitField) |
| 8468 | return Incompatible; |
| 8469 | |
| 8470 | ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); |
| 8471 | return Compatible; |
| 8472 | } |
| 8473 | |
| 8474 | Sema::AssignConvertType |
| 8475 | Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, |
| 8476 | bool Diagnose, |
| 8477 | bool DiagnoseCFAudited, |
| 8478 | bool ConvertRHS) { |
| 8479 | // We need to be able to tell the caller whether we diagnosed a problem, if |
| 8480 | // they ask us to issue diagnostics. |
| 8481 | assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed" ); |
| 8482 | |
| 8483 | // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, |
| 8484 | // we can't avoid *all* modifications at the moment, so we need some somewhere |
| 8485 | // to put the updated value. |
| 8486 | ExprResult LocalRHS = CallerRHS; |
| 8487 | ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; |
| 8488 | |
| 8489 | if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { |
| 8490 | if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { |
| 8491 | if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && |
| 8492 | !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { |
| 8493 | Diag(RHS.get()->getExprLoc(), |
| 8494 | diag::warn_noderef_to_dereferenceable_pointer) |
| 8495 | << RHS.get()->getSourceRange(); |
| 8496 | } |
| 8497 | } |
| 8498 | } |
| 8499 | |
| 8500 | if (getLangOpts().CPlusPlus) { |
| 8501 | if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { |
| 8502 | // C++ 5.17p3: If the left operand is not of class type, the |
| 8503 | // expression is implicitly converted (C++ 4) to the |
| 8504 | // cv-unqualified type of the left operand. |
| 8505 | QualType RHSType = RHS.get()->getType(); |
| 8506 | if (Diagnose) { |
| 8507 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), |
| 8508 | AA_Assigning); |
| 8509 | } else { |
| 8510 | ImplicitConversionSequence ICS = |
| 8511 | TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), |
| 8512 | /*SuppressUserConversions=*/false, |
| 8513 | /*AllowExplicit=*/false, |
| 8514 | /*InOverloadResolution=*/false, |
| 8515 | /*CStyle=*/false, |
| 8516 | /*AllowObjCWritebackConversion=*/false); |
| 8517 | if (ICS.isFailure()) |
| 8518 | return Incompatible; |
| 8519 | RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), |
| 8520 | ICS, AA_Assigning); |
| 8521 | } |
| 8522 | if (RHS.isInvalid()) |
| 8523 | return Incompatible; |
| 8524 | Sema::AssignConvertType result = Compatible; |
| 8525 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 8526 | !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) |
| 8527 | result = IncompatibleObjCWeakRef; |
| 8528 | return result; |
| 8529 | } |
| 8530 | |
| 8531 | // FIXME: Currently, we fall through and treat C++ classes like C |
| 8532 | // structures. |
| 8533 | // FIXME: We also fall through for atomics; not sure what should |
| 8534 | // happen there, though. |
| 8535 | } else if (RHS.get()->getType() == Context.OverloadTy) { |
| 8536 | // As a set of extensions to C, we support overloading on functions. These |
| 8537 | // functions need to be resolved here. |
| 8538 | DeclAccessPair DAP; |
| 8539 | if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( |
| 8540 | RHS.get(), LHSType, /*Complain=*/false, DAP)) |
| 8541 | RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); |
| 8542 | else |
| 8543 | return Incompatible; |
| 8544 | } |
| 8545 | |
| 8546 | // C99 6.5.16.1p1: the left operand is a pointer and the right is |
| 8547 | // a null pointer constant. |
| 8548 | if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || |
| 8549 | LHSType->isBlockPointerType()) && |
| 8550 | RHS.get()->isNullPointerConstant(Context, |
| 8551 | Expr::NPC_ValueDependentIsNull)) { |
| 8552 | if (Diagnose || ConvertRHS) { |
| 8553 | CastKind Kind; |
| 8554 | CXXCastPath Path; |
| 8555 | CheckPointerConversion(RHS.get(), LHSType, Kind, Path, |
| 8556 | /*IgnoreBaseAccess=*/false, Diagnose); |
| 8557 | if (ConvertRHS) |
| 8558 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); |
| 8559 | } |
| 8560 | return Compatible; |
| 8561 | } |
| 8562 | |
| 8563 | // OpenCL queue_t type assignment. |
| 8564 | if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( |
| 8565 | Context, Expr::NPC_ValueDependentIsNull)) { |
| 8566 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); |
| 8567 | return Compatible; |
| 8568 | } |
| 8569 | |
| 8570 | // This check seems unnatural, however it is necessary to ensure the proper |
| 8571 | // conversion of functions/arrays. If the conversion were done for all |
| 8572 | // DeclExpr's (created by ActOnIdExpression), it would mess up the unary |
| 8573 | // expressions that suppress this implicit conversion (&, sizeof). |
| 8574 | // |
| 8575 | // Suppress this for references: C++ 8.5.3p5. |
| 8576 | if (!LHSType->isReferenceType()) { |
| 8577 | // FIXME: We potentially allocate here even if ConvertRHS is false. |
| 8578 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); |
| 8579 | if (RHS.isInvalid()) |
| 8580 | return Incompatible; |
| 8581 | } |
| 8582 | CastKind Kind; |
| 8583 | Sema::AssignConvertType result = |
| 8584 | CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); |
| 8585 | |
| 8586 | // C99 6.5.16.1p2: The value of the right operand is converted to the |
| 8587 | // type of the assignment expression. |
| 8588 | // CheckAssignmentConstraints allows the left-hand side to be a reference, |
| 8589 | // so that we can use references in built-in functions even in C. |
| 8590 | // The getNonReferenceType() call makes sure that the resulting expression |
| 8591 | // does not have reference type. |
| 8592 | if (result != Incompatible && RHS.get()->getType() != LHSType) { |
| 8593 | QualType Ty = LHSType.getNonLValueExprType(Context); |
| 8594 | Expr *E = RHS.get(); |
| 8595 | |
| 8596 | // Check for various Objective-C errors. If we are not reporting |
| 8597 | // diagnostics and just checking for errors, e.g., during overload |
| 8598 | // resolution, return Incompatible to indicate the failure. |
| 8599 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 8600 | CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, |
| 8601 | Diagnose, DiagnoseCFAudited) != ACR_okay) { |
| 8602 | if (!Diagnose) |
| 8603 | return Incompatible; |
| 8604 | } |
| 8605 | if (getLangOpts().ObjC && |
| 8606 | (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, |
| 8607 | E->getType(), E, Diagnose) || |
| 8608 | ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { |
| 8609 | if (!Diagnose) |
| 8610 | return Incompatible; |
| 8611 | // Replace the expression with a corrected version and continue so we |
| 8612 | // can find further errors. |
| 8613 | RHS = E; |
| 8614 | return Compatible; |
| 8615 | } |
| 8616 | |
| 8617 | if (ConvertRHS) |
| 8618 | RHS = ImpCastExprToType(E, Ty, Kind); |
| 8619 | } |
| 8620 | |
| 8621 | return result; |
| 8622 | } |
| 8623 | |
| 8624 | namespace { |
| 8625 | /// The original operand to an operator, prior to the application of the usual |
| 8626 | /// arithmetic conversions and converting the arguments of a builtin operator |
| 8627 | /// candidate. |
| 8628 | struct OriginalOperand { |
| 8629 | explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { |
| 8630 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) |
| 8631 | Op = MTE->GetTemporaryExpr(); |
| 8632 | if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) |
| 8633 | Op = BTE->getSubExpr(); |
| 8634 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { |
| 8635 | Orig = ICE->getSubExprAsWritten(); |
| 8636 | Conversion = ICE->getConversionFunction(); |
| 8637 | } |
| 8638 | } |
| 8639 | |
| 8640 | QualType getType() const { return Orig->getType(); } |
| 8641 | |
| 8642 | Expr *Orig; |
| 8643 | NamedDecl *Conversion; |
| 8644 | }; |
| 8645 | } |
| 8646 | |
| 8647 | QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, |
| 8648 | ExprResult &RHS) { |
| 8649 | OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); |
| 8650 | |
| 8651 | Diag(Loc, diag::err_typecheck_invalid_operands) |
| 8652 | << OrigLHS.getType() << OrigRHS.getType() |
| 8653 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 8654 | |
| 8655 | // If a user-defined conversion was applied to either of the operands prior |
| 8656 | // to applying the built-in operator rules, tell the user about it. |
| 8657 | if (OrigLHS.Conversion) { |
| 8658 | Diag(OrigLHS.Conversion->getLocation(), |
| 8659 | diag::note_typecheck_invalid_operands_converted) |
| 8660 | << 0 << LHS.get()->getType(); |
| 8661 | } |
| 8662 | if (OrigRHS.Conversion) { |
| 8663 | Diag(OrigRHS.Conversion->getLocation(), |
| 8664 | diag::note_typecheck_invalid_operands_converted) |
| 8665 | << 1 << RHS.get()->getType(); |
| 8666 | } |
| 8667 | |
| 8668 | return QualType(); |
| 8669 | } |
| 8670 | |
| 8671 | // Diagnose cases where a scalar was implicitly converted to a vector and |
| 8672 | // diagnose the underlying types. Otherwise, diagnose the error |
| 8673 | // as invalid vector logical operands for non-C++ cases. |
| 8674 | QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, |
| 8675 | ExprResult &RHS) { |
| 8676 | QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); |
| 8677 | QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); |
| 8678 | |
| 8679 | bool LHSNatVec = LHSType->isVectorType(); |
| 8680 | bool RHSNatVec = RHSType->isVectorType(); |
| 8681 | |
| 8682 | if (!(LHSNatVec && RHSNatVec)) { |
| 8683 | Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); |
| 8684 | Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); |
| 8685 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
| 8686 | << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() |
| 8687 | << Vector->getSourceRange(); |
| 8688 | return QualType(); |
| 8689 | } |
| 8690 | |
| 8691 | Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) |
| 8692 | << 1 << LHSType << RHSType << LHS.get()->getSourceRange() |
| 8693 | << RHS.get()->getSourceRange(); |
| 8694 | |
| 8695 | return QualType(); |
| 8696 | } |
| 8697 | |
| 8698 | /// Try to convert a value of non-vector type to a vector type by converting |
| 8699 | /// the type to the element type of the vector and then performing a splat. |
| 8700 | /// If the language is OpenCL, we only use conversions that promote scalar |
| 8701 | /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except |
| 8702 | /// for float->int. |
| 8703 | /// |
| 8704 | /// OpenCL V2.0 6.2.6.p2: |
| 8705 | /// An error shall occur if any scalar operand type has greater rank |
| 8706 | /// than the type of the vector element. |
| 8707 | /// |
| 8708 | /// \param scalar - if non-null, actually perform the conversions |
| 8709 | /// \return true if the operation fails (but without diagnosing the failure) |
| 8710 | static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, |
| 8711 | QualType scalarTy, |
| 8712 | QualType vectorEltTy, |
| 8713 | QualType vectorTy, |
| 8714 | unsigned &DiagID) { |
| 8715 | // The conversion to apply to the scalar before splatting it, |
| 8716 | // if necessary. |
| 8717 | CastKind scalarCast = CK_NoOp; |
| 8718 | |
| 8719 | if (vectorEltTy->isIntegralType(S.Context)) { |
| 8720 | if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || |
| 8721 | (scalarTy->isIntegerType() && |
| 8722 | S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { |
| 8723 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
| 8724 | return true; |
| 8725 | } |
| 8726 | if (!scalarTy->isIntegralType(S.Context)) |
| 8727 | return true; |
| 8728 | scalarCast = CK_IntegralCast; |
| 8729 | } else if (vectorEltTy->isRealFloatingType()) { |
| 8730 | if (scalarTy->isRealFloatingType()) { |
| 8731 | if (S.getLangOpts().OpenCL && |
| 8732 | S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { |
| 8733 | DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; |
| 8734 | return true; |
| 8735 | } |
| 8736 | scalarCast = CK_FloatingCast; |
| 8737 | } |
| 8738 | else if (scalarTy->isIntegralType(S.Context)) |
| 8739 | scalarCast = CK_IntegralToFloating; |
| 8740 | else |
| 8741 | return true; |
| 8742 | } else { |
| 8743 | return true; |
| 8744 | } |
| 8745 | |
| 8746 | // Adjust scalar if desired. |
| 8747 | if (scalar) { |
| 8748 | if (scalarCast != CK_NoOp) |
| 8749 | *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); |
| 8750 | *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); |
| 8751 | } |
| 8752 | return false; |
| 8753 | } |
| 8754 | |
| 8755 | /// Convert vector E to a vector with the same number of elements but different |
| 8756 | /// element type. |
| 8757 | static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { |
| 8758 | const auto *VecTy = E->getType()->getAs<VectorType>(); |
| 8759 | assert(VecTy && "Expression E must be a vector" ); |
| 8760 | QualType NewVecTy = S.Context.getVectorType(ElementType, |
| 8761 | VecTy->getNumElements(), |
| 8762 | VecTy->getVectorKind()); |
| 8763 | |
| 8764 | // Look through the implicit cast. Return the subexpression if its type is |
| 8765 | // NewVecTy. |
| 8766 | if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) |
| 8767 | if (ICE->getSubExpr()->getType() == NewVecTy) |
| 8768 | return ICE->getSubExpr(); |
| 8769 | |
| 8770 | auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; |
| 8771 | return S.ImpCastExprToType(E, NewVecTy, Cast); |
| 8772 | } |
| 8773 | |
| 8774 | /// Test if a (constant) integer Int can be casted to another integer type |
| 8775 | /// IntTy without losing precision. |
| 8776 | static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, |
| 8777 | QualType OtherIntTy) { |
| 8778 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
| 8779 | |
| 8780 | // Reject cases where the value of the Int is unknown as that would |
| 8781 | // possibly cause truncation, but accept cases where the scalar can be |
| 8782 | // demoted without loss of precision. |
| 8783 | Expr::EvalResult EVResult; |
| 8784 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); |
| 8785 | int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); |
| 8786 | bool IntSigned = IntTy->hasSignedIntegerRepresentation(); |
| 8787 | bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); |
| 8788 | |
| 8789 | if (CstInt) { |
| 8790 | // If the scalar is constant and is of a higher order and has more active |
| 8791 | // bits that the vector element type, reject it. |
| 8792 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 8793 | unsigned NumBits = IntSigned |
| 8794 | ? (Result.isNegative() ? Result.getMinSignedBits() |
| 8795 | : Result.getActiveBits()) |
| 8796 | : Result.getActiveBits(); |
| 8797 | if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) |
| 8798 | return true; |
| 8799 | |
| 8800 | // If the signedness of the scalar type and the vector element type |
| 8801 | // differs and the number of bits is greater than that of the vector |
| 8802 | // element reject it. |
| 8803 | return (IntSigned != OtherIntSigned && |
| 8804 | NumBits > S.Context.getIntWidth(OtherIntTy)); |
| 8805 | } |
| 8806 | |
| 8807 | // Reject cases where the value of the scalar is not constant and it's |
| 8808 | // order is greater than that of the vector element type. |
| 8809 | return (Order < 0); |
| 8810 | } |
| 8811 | |
| 8812 | /// Test if a (constant) integer Int can be casted to floating point type |
| 8813 | /// FloatTy without losing precision. |
| 8814 | static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, |
| 8815 | QualType FloatTy) { |
| 8816 | QualType IntTy = Int->get()->getType().getUnqualifiedType(); |
| 8817 | |
| 8818 | // Determine if the integer constant can be expressed as a floating point |
| 8819 | // number of the appropriate type. |
| 8820 | Expr::EvalResult EVResult; |
| 8821 | bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); |
| 8822 | |
| 8823 | uint64_t Bits = 0; |
| 8824 | if (CstInt) { |
| 8825 | // Reject constants that would be truncated if they were converted to |
| 8826 | // the floating point type. Test by simple to/from conversion. |
| 8827 | // FIXME: Ideally the conversion to an APFloat and from an APFloat |
| 8828 | // could be avoided if there was a convertFromAPInt method |
| 8829 | // which could signal back if implicit truncation occurred. |
| 8830 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 8831 | llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); |
| 8832 | Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), |
| 8833 | llvm::APFloat::rmTowardZero); |
| 8834 | llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), |
| 8835 | !IntTy->hasSignedIntegerRepresentation()); |
| 8836 | bool Ignored = false; |
| 8837 | Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, |
| 8838 | &Ignored); |
| 8839 | if (Result != ConvertBack) |
| 8840 | return true; |
| 8841 | } else { |
| 8842 | // Reject types that cannot be fully encoded into the mantissa of |
| 8843 | // the float. |
| 8844 | Bits = S.Context.getTypeSize(IntTy); |
| 8845 | unsigned FloatPrec = llvm::APFloat::semanticsPrecision( |
| 8846 | S.Context.getFloatTypeSemantics(FloatTy)); |
| 8847 | if (Bits > FloatPrec) |
| 8848 | return true; |
| 8849 | } |
| 8850 | |
| 8851 | return false; |
| 8852 | } |
| 8853 | |
| 8854 | /// Attempt to convert and splat Scalar into a vector whose types matches |
| 8855 | /// Vector following GCC conversion rules. The rule is that implicit |
| 8856 | /// conversion can occur when Scalar can be casted to match Vector's element |
| 8857 | /// type without causing truncation of Scalar. |
| 8858 | static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, |
| 8859 | ExprResult *Vector) { |
| 8860 | QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); |
| 8861 | QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); |
| 8862 | const VectorType *VT = VectorTy->getAs<VectorType>(); |
| 8863 | |
| 8864 | assert(!isa<ExtVectorType>(VT) && |
| 8865 | "ExtVectorTypes should not be handled here!" ); |
| 8866 | |
| 8867 | QualType VectorEltTy = VT->getElementType(); |
| 8868 | |
| 8869 | // Reject cases where the vector element type or the scalar element type are |
| 8870 | // not integral or floating point types. |
| 8871 | if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) |
| 8872 | return true; |
| 8873 | |
| 8874 | // The conversion to apply to the scalar before splatting it, |
| 8875 | // if necessary. |
| 8876 | CastKind ScalarCast = CK_NoOp; |
| 8877 | |
| 8878 | // Accept cases where the vector elements are integers and the scalar is |
| 8879 | // an integer. |
| 8880 | // FIXME: Notionally if the scalar was a floating point value with a precise |
| 8881 | // integral representation, we could cast it to an appropriate integer |
| 8882 | // type and then perform the rest of the checks here. GCC will perform |
| 8883 | // this conversion in some cases as determined by the input language. |
| 8884 | // We should accept it on a language independent basis. |
| 8885 | if (VectorEltTy->isIntegralType(S.Context) && |
| 8886 | ScalarTy->isIntegralType(S.Context) && |
| 8887 | S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { |
| 8888 | |
| 8889 | if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) |
| 8890 | return true; |
| 8891 | |
| 8892 | ScalarCast = CK_IntegralCast; |
| 8893 | } else if (VectorEltTy->isRealFloatingType()) { |
| 8894 | if (ScalarTy->isRealFloatingType()) { |
| 8895 | |
| 8896 | // Reject cases where the scalar type is not a constant and has a higher |
| 8897 | // Order than the vector element type. |
| 8898 | llvm::APFloat Result(0.0); |
| 8899 | bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); |
| 8900 | int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); |
| 8901 | if (!CstScalar && Order < 0) |
| 8902 | return true; |
| 8903 | |
| 8904 | // If the scalar cannot be safely casted to the vector element type, |
| 8905 | // reject it. |
| 8906 | if (CstScalar) { |
| 8907 | bool Truncated = false; |
| 8908 | Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), |
| 8909 | llvm::APFloat::rmNearestTiesToEven, &Truncated); |
| 8910 | if (Truncated) |
| 8911 | return true; |
| 8912 | } |
| 8913 | |
| 8914 | ScalarCast = CK_FloatingCast; |
| 8915 | } else if (ScalarTy->isIntegralType(S.Context)) { |
| 8916 | if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) |
| 8917 | return true; |
| 8918 | |
| 8919 | ScalarCast = CK_IntegralToFloating; |
| 8920 | } else |
| 8921 | return true; |
| 8922 | } |
| 8923 | |
| 8924 | // Adjust scalar if desired. |
| 8925 | if (Scalar) { |
| 8926 | if (ScalarCast != CK_NoOp) |
| 8927 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); |
| 8928 | *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); |
| 8929 | } |
| 8930 | return false; |
| 8931 | } |
| 8932 | |
| 8933 | QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, |
| 8934 | SourceLocation Loc, bool IsCompAssign, |
| 8935 | bool AllowBothBool, |
| 8936 | bool AllowBoolConversions) { |
| 8937 | if (!IsCompAssign) { |
| 8938 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); |
| 8939 | if (LHS.isInvalid()) |
| 8940 | return QualType(); |
| 8941 | } |
| 8942 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); |
| 8943 | if (RHS.isInvalid()) |
| 8944 | return QualType(); |
| 8945 | |
| 8946 | // For conversion purposes, we ignore any qualifiers. |
| 8947 | // For example, "const float" and "float" are equivalent. |
| 8948 | QualType LHSType = LHS.get()->getType().getUnqualifiedType(); |
| 8949 | QualType RHSType = RHS.get()->getType().getUnqualifiedType(); |
| 8950 | |
| 8951 | const VectorType *LHSVecType = LHSType->getAs<VectorType>(); |
| 8952 | const VectorType *RHSVecType = RHSType->getAs<VectorType>(); |
| 8953 | assert(LHSVecType || RHSVecType); |
| 8954 | |
| 8955 | // AltiVec-style "vector bool op vector bool" combinations are allowed |
| 8956 | // for some operators but not others. |
| 8957 | if (!AllowBothBool && |
| 8958 | LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && |
| 8959 | RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) |
| 8960 | return InvalidOperands(Loc, LHS, RHS); |
| 8961 | |
| 8962 | // If the vector types are identical, return. |
| 8963 | if (Context.hasSameType(LHSType, RHSType)) |
| 8964 | return LHSType; |
| 8965 | |
| 8966 | // If we have compatible AltiVec and GCC vector types, use the AltiVec type. |
| 8967 | if (LHSVecType && RHSVecType && |
| 8968 | Context.areCompatibleVectorTypes(LHSType, RHSType)) { |
| 8969 | if (isa<ExtVectorType>(LHSVecType)) { |
| 8970 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); |
| 8971 | return LHSType; |
| 8972 | } |
| 8973 | |
| 8974 | if (!IsCompAssign) |
| 8975 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); |
| 8976 | return RHSType; |
| 8977 | } |
| 8978 | |
| 8979 | // AllowBoolConversions says that bool and non-bool AltiVec vectors |
| 8980 | // can be mixed, with the result being the non-bool type. The non-bool |
| 8981 | // operand must have integer element type. |
| 8982 | if (AllowBoolConversions && LHSVecType && RHSVecType && |
| 8983 | LHSVecType->getNumElements() == RHSVecType->getNumElements() && |
| 8984 | (Context.getTypeSize(LHSVecType->getElementType()) == |
| 8985 | Context.getTypeSize(RHSVecType->getElementType()))) { |
| 8986 | if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && |
| 8987 | LHSVecType->getElementType()->isIntegerType() && |
| 8988 | RHSVecType->getVectorKind() == VectorType::AltiVecBool) { |
| 8989 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); |
| 8990 | return LHSType; |
| 8991 | } |
| 8992 | if (!IsCompAssign && |
| 8993 | LHSVecType->getVectorKind() == VectorType::AltiVecBool && |
| 8994 | RHSVecType->getVectorKind() == VectorType::AltiVecVector && |
| 8995 | RHSVecType->getElementType()->isIntegerType()) { |
| 8996 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); |
| 8997 | return RHSType; |
| 8998 | } |
| 8999 | } |
| 9000 | |
| 9001 | // If there's a vector type and a scalar, try to convert the scalar to |
| 9002 | // the vector element type and splat. |
| 9003 | unsigned DiagID = diag::err_typecheck_vector_not_convertable; |
| 9004 | if (!RHSVecType) { |
| 9005 | if (isa<ExtVectorType>(LHSVecType)) { |
| 9006 | if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, |
| 9007 | LHSVecType->getElementType(), LHSType, |
| 9008 | DiagID)) |
| 9009 | return LHSType; |
| 9010 | } else { |
| 9011 | if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) |
| 9012 | return LHSType; |
| 9013 | } |
| 9014 | } |
| 9015 | if (!LHSVecType) { |
| 9016 | if (isa<ExtVectorType>(RHSVecType)) { |
| 9017 | if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), |
| 9018 | LHSType, RHSVecType->getElementType(), |
| 9019 | RHSType, DiagID)) |
| 9020 | return RHSType; |
| 9021 | } else { |
| 9022 | if (LHS.get()->getValueKind() == VK_LValue || |
| 9023 | !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) |
| 9024 | return RHSType; |
| 9025 | } |
| 9026 | } |
| 9027 | |
| 9028 | // FIXME: The code below also handles conversion between vectors and |
| 9029 | // non-scalars, we should break this down into fine grained specific checks |
| 9030 | // and emit proper diagnostics. |
| 9031 | QualType VecType = LHSVecType ? LHSType : RHSType; |
| 9032 | const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; |
| 9033 | QualType OtherType = LHSVecType ? RHSType : LHSType; |
| 9034 | ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; |
| 9035 | if (isLaxVectorConversion(OtherType, VecType)) { |
| 9036 | // If we're allowing lax vector conversions, only the total (data) size |
| 9037 | // needs to be the same. For non compound assignment, if one of the types is |
| 9038 | // scalar, the result is always the vector type. |
| 9039 | if (!IsCompAssign) { |
| 9040 | *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); |
| 9041 | return VecType; |
| 9042 | // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding |
| 9043 | // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' |
| 9044 | // type. Note that this is already done by non-compound assignments in |
| 9045 | // CheckAssignmentConstraints. If it's a scalar type, only bitcast for |
| 9046 | // <1 x T> -> T. The result is also a vector type. |
| 9047 | } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || |
| 9048 | (OtherType->isScalarType() && VT->getNumElements() == 1)) { |
| 9049 | ExprResult *RHSExpr = &RHS; |
| 9050 | *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); |
| 9051 | return VecType; |
| 9052 | } |
| 9053 | } |
| 9054 | |
| 9055 | // Okay, the expression is invalid. |
| 9056 | |
| 9057 | // If there's a non-vector, non-real operand, diagnose that. |
| 9058 | if ((!RHSVecType && !RHSType->isRealType()) || |
| 9059 | (!LHSVecType && !LHSType->isRealType())) { |
| 9060 | Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) |
| 9061 | << LHSType << RHSType |
| 9062 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9063 | return QualType(); |
| 9064 | } |
| 9065 | |
| 9066 | // OpenCL V1.1 6.2.6.p1: |
| 9067 | // If the operands are of more than one vector type, then an error shall |
| 9068 | // occur. Implicit conversions between vector types are not permitted, per |
| 9069 | // section 6.2.1. |
| 9070 | if (getLangOpts().OpenCL && |
| 9071 | RHSVecType && isa<ExtVectorType>(RHSVecType) && |
| 9072 | LHSVecType && isa<ExtVectorType>(LHSVecType)) { |
| 9073 | Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType |
| 9074 | << RHSType; |
| 9075 | return QualType(); |
| 9076 | } |
| 9077 | |
| 9078 | |
| 9079 | // If there is a vector type that is not a ExtVector and a scalar, we reach |
| 9080 | // this point if scalar could not be converted to the vector's element type |
| 9081 | // without truncation. |
| 9082 | if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || |
| 9083 | (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { |
| 9084 | QualType Scalar = LHSVecType ? RHSType : LHSType; |
| 9085 | QualType Vector = LHSVecType ? LHSType : RHSType; |
| 9086 | unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; |
| 9087 | Diag(Loc, |
| 9088 | diag::err_typecheck_vector_not_convertable_implict_truncation) |
| 9089 | << ScalarOrVector << Scalar << Vector; |
| 9090 | |
| 9091 | return QualType(); |
| 9092 | } |
| 9093 | |
| 9094 | // Otherwise, use the generic diagnostic. |
| 9095 | Diag(Loc, DiagID) |
| 9096 | << LHSType << RHSType |
| 9097 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9098 | return QualType(); |
| 9099 | } |
| 9100 | |
| 9101 | // checkArithmeticNull - Detect when a NULL constant is used improperly in an |
| 9102 | // expression. These are mainly cases where the null pointer is used as an |
| 9103 | // integer instead of a pointer. |
| 9104 | static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 9105 | SourceLocation Loc, bool IsCompare) { |
| 9106 | // The canonical way to check for a GNU null is with isNullPointerConstant, |
| 9107 | // but we use a bit of a hack here for speed; this is a relatively |
| 9108 | // hot path, and isNullPointerConstant is slow. |
| 9109 | bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); |
| 9110 | bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); |
| 9111 | |
| 9112 | QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); |
| 9113 | |
| 9114 | // Avoid analyzing cases where the result will either be invalid (and |
| 9115 | // diagnosed as such) or entirely valid and not something to warn about. |
| 9116 | if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || |
| 9117 | NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) |
| 9118 | return; |
| 9119 | |
| 9120 | // Comparison operations would not make sense with a null pointer no matter |
| 9121 | // what the other expression is. |
| 9122 | if (!IsCompare) { |
| 9123 | S.Diag(Loc, diag::warn_null_in_arithmetic_operation) |
| 9124 | << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) |
| 9125 | << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); |
| 9126 | return; |
| 9127 | } |
| 9128 | |
| 9129 | // The rest of the operations only make sense with a null pointer |
| 9130 | // if the other expression is a pointer. |
| 9131 | if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || |
| 9132 | NonNullType->canDecayToPointerType()) |
| 9133 | return; |
| 9134 | |
| 9135 | S.Diag(Loc, diag::warn_null_in_comparison_operation) |
| 9136 | << LHSNull /* LHS is NULL */ << NonNullType |
| 9137 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9138 | } |
| 9139 | |
| 9140 | static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, |
| 9141 | SourceLocation Loc) { |
| 9142 | const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); |
| 9143 | const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); |
| 9144 | if (!LUE || !RUE) |
| 9145 | return; |
| 9146 | if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || |
| 9147 | RUE->getKind() != UETT_SizeOf) |
| 9148 | return; |
| 9149 | |
| 9150 | QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); |
| 9151 | QualType RHSTy; |
| 9152 | |
| 9153 | if (RUE->isArgumentType()) |
| 9154 | RHSTy = RUE->getArgumentType(); |
| 9155 | else |
| 9156 | RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); |
| 9157 | |
| 9158 | if (!LHSTy->isPointerType() || RHSTy->isPointerType()) |
| 9159 | return; |
| 9160 | if (LHSTy->getPointeeType() != RHSTy) |
| 9161 | return; |
| 9162 | |
| 9163 | S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); |
| 9164 | } |
| 9165 | |
| 9166 | static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, |
| 9167 | ExprResult &RHS, |
| 9168 | SourceLocation Loc, bool IsDiv) { |
| 9169 | // Check for division/remainder by zero. |
| 9170 | Expr::EvalResult RHSValue; |
| 9171 | if (!RHS.get()->isValueDependent() && |
| 9172 | RHS.get()->EvaluateAsInt(RHSValue, S.Context) && |
| 9173 | RHSValue.Val.getInt() == 0) |
| 9174 | S.DiagRuntimeBehavior(Loc, RHS.get(), |
| 9175 | S.PDiag(diag::warn_remainder_division_by_zero) |
| 9176 | << IsDiv << RHS.get()->getSourceRange()); |
| 9177 | } |
| 9178 | |
| 9179 | QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, |
| 9180 | SourceLocation Loc, |
| 9181 | bool IsCompAssign, bool IsDiv) { |
| 9182 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); |
| 9183 | |
| 9184 | if (LHS.get()->getType()->isVectorType() || |
| 9185 | RHS.get()->getType()->isVectorType()) |
| 9186 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 9187 | /*AllowBothBool*/getLangOpts().AltiVec, |
| 9188 | /*AllowBoolConversions*/false); |
| 9189 | |
| 9190 | QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); |
| 9191 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 9192 | return QualType(); |
| 9193 | |
| 9194 | |
| 9195 | if (compType.isNull() || !compType->isArithmeticType()) |
| 9196 | return InvalidOperands(Loc, LHS, RHS); |
| 9197 | if (IsDiv) { |
| 9198 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); |
| 9199 | DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); |
| 9200 | } |
| 9201 | return compType; |
| 9202 | } |
| 9203 | |
| 9204 | QualType Sema::CheckRemainderOperands( |
| 9205 | ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { |
| 9206 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); |
| 9207 | |
| 9208 | // Remainder in offset mode will not work for alignment checks since it |
| 9209 | // doesn't take the base into account so we warn then |
| 9210 | if (getLangOpts().cheriUIntCapUsesOffset() && |
| 9211 | (LHS.get()->getType()->isCHERICapabilityType(Context) || |
| 9212 | RHS.get()->getType()->isCHERICapabilityType(Context))) |
| 9213 | DiagRuntimeBehavior( |
| 9214 | Loc, RHS.get(), |
| 9215 | PDiag(diag::warn_uintcap_bad_bitwise_op) |
| 9216 | << 2 /*=modulo*/ << 1 /* used for alignment checks */ |
| 9217 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()); |
| 9218 | |
| 9219 | if (LHS.get()->getType()->isVectorType() || |
| 9220 | RHS.get()->getType()->isVectorType()) { |
| 9221 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
| 9222 | RHS.get()->getType()->hasIntegerRepresentation()) |
| 9223 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 9224 | /*AllowBothBool*/getLangOpts().AltiVec, |
| 9225 | /*AllowBoolConversions*/false); |
| 9226 | return InvalidOperands(Loc, LHS, RHS); |
| 9227 | } |
| 9228 | |
| 9229 | QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); |
| 9230 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 9231 | return QualType(); |
| 9232 | |
| 9233 | if (compType.isNull() || !compType->isIntegerType()) |
| 9234 | return InvalidOperands(Loc, LHS, RHS); |
| 9235 | DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); |
| 9236 | return compType; |
| 9237 | } |
| 9238 | |
| 9239 | /// Diagnose invalid arithmetic on two void pointers. |
| 9240 | static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, |
| 9241 | Expr *LHSExpr, Expr *RHSExpr) { |
| 9242 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
| 9243 | ? diag::err_typecheck_pointer_arith_void_type |
| 9244 | : diag::ext_gnu_void_ptr) |
| 9245 | << 1 /* two pointers */ << LHSExpr->getSourceRange() |
| 9246 | << RHSExpr->getSourceRange(); |
| 9247 | } |
| 9248 | |
| 9249 | /// Diagnose invalid arithmetic on a void pointer. |
| 9250 | static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, |
| 9251 | Expr *Pointer) { |
| 9252 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
| 9253 | ? diag::err_typecheck_pointer_arith_void_type |
| 9254 | : diag::ext_gnu_void_ptr) |
| 9255 | << 0 /* one pointer */ << Pointer->getSourceRange(); |
| 9256 | } |
| 9257 | |
| 9258 | /// Diagnose invalid arithmetic on a null pointer. |
| 9259 | /// |
| 9260 | /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' |
| 9261 | /// idiom, which we recognize as a GNU extension. |
| 9262 | /// |
| 9263 | static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, |
| 9264 | Expr *Pointer, bool IsGNUIdiom) { |
| 9265 | if (IsGNUIdiom) |
| 9266 | S.Diag(Loc, diag::warn_gnu_null_ptr_arith) |
| 9267 | << Pointer->getSourceRange(); |
| 9268 | else |
| 9269 | S.Diag(Loc, diag::warn_pointer_arith_null_ptr) |
| 9270 | << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); |
| 9271 | } |
| 9272 | |
| 9273 | /// Diagnose invalid arithmetic on two function pointers. |
| 9274 | static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, |
| 9275 | Expr *LHS, Expr *RHS) { |
| 9276 | assert(LHS->getType()->isAnyPointerType()); |
| 9277 | assert(RHS->getType()->isAnyPointerType()); |
| 9278 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
| 9279 | ? diag::err_typecheck_pointer_arith_function_type |
| 9280 | : diag::ext_gnu_ptr_func_arith) |
| 9281 | << 1 /* two pointers */ << LHS->getType()->getPointeeType() |
| 9282 | // We only show the second type if it differs from the first. |
| 9283 | << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), |
| 9284 | RHS->getType()) |
| 9285 | << RHS->getType()->getPointeeType() |
| 9286 | << LHS->getSourceRange() << RHS->getSourceRange(); |
| 9287 | } |
| 9288 | |
| 9289 | /// Diagnose invalid arithmetic on a function pointer. |
| 9290 | static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, |
| 9291 | Expr *Pointer) { |
| 9292 | assert(Pointer->getType()->isAnyPointerType()); |
| 9293 | S.Diag(Loc, S.getLangOpts().CPlusPlus |
| 9294 | ? diag::err_typecheck_pointer_arith_function_type |
| 9295 | : diag::ext_gnu_ptr_func_arith) |
| 9296 | << 0 /* one pointer */ << Pointer->getType()->getPointeeType() |
| 9297 | << 0 /* one pointer, so only one type */ |
| 9298 | << Pointer->getSourceRange(); |
| 9299 | } |
| 9300 | |
| 9301 | /// Emit error if Operand is incomplete pointer type |
| 9302 | /// |
| 9303 | /// \returns True if pointer has incomplete type |
| 9304 | static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, |
| 9305 | Expr *Operand) { |
| 9306 | QualType ResType = Operand->getType(); |
| 9307 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
| 9308 | ResType = ResAtomicType->getValueType(); |
| 9309 | |
| 9310 | assert(ResType->isAnyPointerType() && !ResType->isDependentType()); |
| 9311 | QualType PointeeTy = ResType->getPointeeType(); |
| 9312 | return S.RequireCompleteType(Loc, PointeeTy, |
| 9313 | diag::err_typecheck_arithmetic_incomplete_type, |
| 9314 | PointeeTy, Operand->getSourceRange()); |
| 9315 | } |
| 9316 | |
| 9317 | /// Check the validity of an arithmetic pointer operand. |
| 9318 | /// |
| 9319 | /// If the operand has pointer type, this code will check for pointer types |
| 9320 | /// which are invalid in arithmetic operations. These will be diagnosed |
| 9321 | /// appropriately, including whether or not the use is supported as an |
| 9322 | /// extension. |
| 9323 | /// |
| 9324 | /// \returns True when the operand is valid to use (even if as an extension). |
| 9325 | static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, |
| 9326 | Expr *Operand) { |
| 9327 | QualType ResType = Operand->getType(); |
| 9328 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
| 9329 | ResType = ResAtomicType->getValueType(); |
| 9330 | |
| 9331 | if (!ResType->isAnyPointerType()) return true; |
| 9332 | |
| 9333 | QualType PointeeTy = ResType->getPointeeType(); |
| 9334 | if (PointeeTy->isVoidType()) { |
| 9335 | diagnoseArithmeticOnVoidPointer(S, Loc, Operand); |
| 9336 | return !S.getLangOpts().CPlusPlus; |
| 9337 | } |
| 9338 | if (PointeeTy->isFunctionType()) { |
| 9339 | diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); |
| 9340 | return !S.getLangOpts().CPlusPlus; |
| 9341 | } |
| 9342 | |
| 9343 | if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; |
| 9344 | |
| 9345 | return true; |
| 9346 | } |
| 9347 | |
| 9348 | /// Check the validity of a binary arithmetic operation w.r.t. pointer |
| 9349 | /// operands. |
| 9350 | /// |
| 9351 | /// This routine will diagnose any invalid arithmetic on pointer operands much |
| 9352 | /// like \see checkArithmeticOpPointerOperand. However, it has special logic |
| 9353 | /// for emitting a single diagnostic even for operations where both LHS and RHS |
| 9354 | /// are (potentially problematic) pointers. |
| 9355 | /// |
| 9356 | /// \returns True when the operand is valid to use (even if as an extension). |
| 9357 | static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, |
| 9358 | Expr *LHSExpr, Expr *RHSExpr) { |
| 9359 | bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); |
| 9360 | bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); |
| 9361 | if (!isLHSPointer && !isRHSPointer) return true; |
| 9362 | |
| 9363 | QualType LHSPointeeTy, RHSPointeeTy; |
| 9364 | if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); |
| 9365 | if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); |
| 9366 | |
| 9367 | // if both are pointers check if operation is valid wrt address spaces |
| 9368 | if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { |
| 9369 | const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); |
| 9370 | const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); |
| 9371 | ASTContext &Context = S.getASTContext(); |
| 9372 | const Expr::NullPointerConstantKind LHSNullKind = |
| 9373 | LHSExpr->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); |
| 9374 | const Expr::NullPointerConstantKind RHSNullKind = |
| 9375 | RHSExpr->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); |
| 9376 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; |
| 9377 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
| 9378 | if (!RHSIsNull && !LHSIsNull && |
| 9379 | !lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { |
| 9380 | S.Diag(Loc, |
| 9381 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
| 9382 | << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ |
| 9383 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); |
| 9384 | return false; |
| 9385 | } |
| 9386 | } |
| 9387 | |
| 9388 | // Check for arithmetic on pointers to incomplete types. |
| 9389 | bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); |
| 9390 | bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); |
| 9391 | if (isLHSVoidPtr || isRHSVoidPtr) { |
| 9392 | if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); |
| 9393 | else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); |
| 9394 | else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); |
| 9395 | |
| 9396 | return !S.getLangOpts().CPlusPlus; |
| 9397 | } |
| 9398 | |
| 9399 | bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); |
| 9400 | bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); |
| 9401 | if (isLHSFuncPtr || isRHSFuncPtr) { |
| 9402 | if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); |
| 9403 | else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, |
| 9404 | RHSExpr); |
| 9405 | else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); |
| 9406 | |
| 9407 | return !S.getLangOpts().CPlusPlus; |
| 9408 | } |
| 9409 | |
| 9410 | if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) |
| 9411 | return false; |
| 9412 | if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) |
| 9413 | return false; |
| 9414 | |
| 9415 | return true; |
| 9416 | } |
| 9417 | |
| 9418 | /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string |
| 9419 | /// literal. |
| 9420 | static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, |
| 9421 | Expr *LHSExpr, Expr *RHSExpr) { |
| 9422 | StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); |
| 9423 | Expr* IndexExpr = RHSExpr; |
| 9424 | if (!StrExpr) { |
| 9425 | StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); |
| 9426 | IndexExpr = LHSExpr; |
| 9427 | } |
| 9428 | |
| 9429 | bool IsStringPlusInt = StrExpr && |
| 9430 | IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); |
| 9431 | if (!IsStringPlusInt || IndexExpr->isValueDependent()) |
| 9432 | return; |
| 9433 | |
| 9434 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 9435 | Self.Diag(OpLoc, diag::warn_string_plus_int) |
| 9436 | << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); |
| 9437 | |
| 9438 | // Only print a fixit for "str" + int, not for int + "str". |
| 9439 | if (IndexExpr == RHSExpr) { |
| 9440 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); |
| 9441 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) |
| 9442 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&" ) |
| 9443 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[" ) |
| 9444 | << FixItHint::CreateInsertion(EndLoc, "]" ); |
| 9445 | } else |
| 9446 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); |
| 9447 | } |
| 9448 | |
| 9449 | /// Emit a warning when adding a char literal to a string. |
| 9450 | static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, |
| 9451 | Expr *LHSExpr, Expr *RHSExpr) { |
| 9452 | const Expr *StringRefExpr = LHSExpr; |
| 9453 | const CharacterLiteral *CharExpr = |
| 9454 | dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); |
| 9455 | |
| 9456 | if (!CharExpr) { |
| 9457 | CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); |
| 9458 | StringRefExpr = RHSExpr; |
| 9459 | } |
| 9460 | |
| 9461 | if (!CharExpr || !StringRefExpr) |
| 9462 | return; |
| 9463 | |
| 9464 | const QualType StringType = StringRefExpr->getType(); |
| 9465 | |
| 9466 | // Return if not a PointerType. |
| 9467 | if (!StringType->isAnyPointerType()) |
| 9468 | return; |
| 9469 | |
| 9470 | // Return if not a CharacterType. |
| 9471 | if (!StringType->getPointeeType()->isAnyCharacterType()) |
| 9472 | return; |
| 9473 | |
| 9474 | ASTContext &Ctx = Self.getASTContext(); |
| 9475 | SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 9476 | |
| 9477 | const QualType CharType = CharExpr->getType(); |
| 9478 | if (!CharType->isAnyCharacterType() && |
| 9479 | CharType->isIntegerType() && |
| 9480 | llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { |
| 9481 | Self.Diag(OpLoc, diag::warn_string_plus_char) |
| 9482 | << DiagRange << Ctx.CharTy; |
| 9483 | } else { |
| 9484 | Self.Diag(OpLoc, diag::warn_string_plus_char) |
| 9485 | << DiagRange << CharExpr->getType(); |
| 9486 | } |
| 9487 | |
| 9488 | // Only print a fixit for str + char, not for char + str. |
| 9489 | if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { |
| 9490 | SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); |
| 9491 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) |
| 9492 | << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&" ) |
| 9493 | << FixItHint::CreateReplacement(SourceRange(OpLoc), "[" ) |
| 9494 | << FixItHint::CreateInsertion(EndLoc, "]" ); |
| 9495 | } else { |
| 9496 | Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); |
| 9497 | } |
| 9498 | } |
| 9499 | |
| 9500 | /// Emit error when two pointers are incompatible. |
| 9501 | static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, |
| 9502 | Expr *LHSExpr, Expr *RHSExpr) { |
| 9503 | assert(LHSExpr->getType()->isAnyPointerType()); |
| 9504 | assert(RHSExpr->getType()->isAnyPointerType()); |
| 9505 | S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) |
| 9506 | << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() |
| 9507 | << RHSExpr->getSourceRange(); |
| 9508 | } |
| 9509 | |
| 9510 | // C99 6.5.6 |
| 9511 | QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, |
| 9512 | SourceLocation Loc, BinaryOperatorKind Opc, |
| 9513 | QualType* CompLHSTy) { |
| 9514 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); |
| 9515 | |
| 9516 | if (LHS.get()->getType()->isVectorType() || |
| 9517 | RHS.get()->getType()->isVectorType()) { |
| 9518 | QualType compType = CheckVectorOperands( |
| 9519 | LHS, RHS, Loc, CompLHSTy, |
| 9520 | /*AllowBothBool*/getLangOpts().AltiVec, |
| 9521 | /*AllowBoolConversions*/getLangOpts().ZVector); |
| 9522 | if (CompLHSTy) *CompLHSTy = compType; |
| 9523 | return compType; |
| 9524 | } |
| 9525 | |
| 9526 | QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); |
| 9527 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 9528 | return QualType(); |
| 9529 | |
| 9530 | // Diagnose "string literal" '+' int and string '+' "char literal". |
| 9531 | if (Opc == BO_Add) { |
| 9532 | diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); |
| 9533 | diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); |
| 9534 | } |
| 9535 | |
| 9536 | // handle the common case first (both operands are arithmetic). |
| 9537 | if (!compType.isNull() && compType->isArithmeticType()) { |
| 9538 | if (CompLHSTy) *CompLHSTy = compType; |
| 9539 | return compType; |
| 9540 | } |
| 9541 | |
| 9542 | // Type-checking. Ultimately the pointer's going to be in PExp; |
| 9543 | // note that we bias towards the LHS being the pointer. |
| 9544 | Expr *PExp = LHS.get(), *IExp = RHS.get(); |
| 9545 | |
| 9546 | bool isObjCPointer; |
| 9547 | if (PExp->getType()->isPointerType()) { |
| 9548 | isObjCPointer = false; |
| 9549 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
| 9550 | isObjCPointer = true; |
| 9551 | } else { |
| 9552 | std::swap(PExp, IExp); |
| 9553 | if (PExp->getType()->isPointerType()) { |
| 9554 | isObjCPointer = false; |
| 9555 | } else if (PExp->getType()->isObjCObjectPointerType()) { |
| 9556 | isObjCPointer = true; |
| 9557 | } else { |
| 9558 | return InvalidOperands(Loc, LHS, RHS); |
| 9559 | } |
| 9560 | } |
| 9561 | assert(PExp->getType()->isAnyPointerType()); |
| 9562 | |
| 9563 | if (!IExp->getType()->isIntegerType()) |
| 9564 | return InvalidOperands(Loc, LHS, RHS); |
| 9565 | |
| 9566 | // Adding to a null pointer results in undefined behavior. |
| 9567 | if (PExp->IgnoreParenCasts()->isNullPointerConstant( |
| 9568 | Context, Expr::NPC_ValueDependentIsNotNull)) { |
| 9569 | // In C++ adding zero to a null pointer is defined. |
| 9570 | Expr::EvalResult KnownVal; |
| 9571 | if (!getLangOpts().CPlusPlus || |
| 9572 | (!IExp->isValueDependent() && |
| 9573 | (!IExp->EvaluateAsInt(KnownVal, Context) || |
| 9574 | KnownVal.Val.getInt() != 0))) { |
| 9575 | // Check the conditions to see if this is the 'p = nullptr + n' idiom. |
| 9576 | bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( |
| 9577 | Context, BO_Add, PExp, IExp); |
| 9578 | diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); |
| 9579 | } |
| 9580 | } |
| 9581 | |
| 9582 | if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) |
| 9583 | return QualType(); |
| 9584 | |
| 9585 | if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) |
| 9586 | return QualType(); |
| 9587 | |
| 9588 | // Check array bounds for pointer arithemtic |
| 9589 | CheckArrayAccess(PExp, IExp); |
| 9590 | |
| 9591 | if (CompLHSTy) { |
| 9592 | QualType LHSTy = Context.isPromotableBitField(LHS.get()); |
| 9593 | if (LHSTy.isNull()) { |
| 9594 | LHSTy = LHS.get()->getType(); |
| 9595 | if (LHSTy->isPromotableIntegerType()) |
| 9596 | LHSTy = Context.getPromotedIntegerType(LHSTy); |
| 9597 | } |
| 9598 | *CompLHSTy = LHSTy; |
| 9599 | } |
| 9600 | |
| 9601 | return PExp->getType(); |
| 9602 | } |
| 9603 | |
| 9604 | // C99 6.5.6 |
| 9605 | QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, |
| 9606 | SourceLocation Loc, |
| 9607 | QualType* CompLHSTy) { |
| 9608 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); |
| 9609 | |
| 9610 | if (LHS.get()->getType()->isVectorType() || |
| 9611 | RHS.get()->getType()->isVectorType()) { |
| 9612 | QualType compType = CheckVectorOperands( |
| 9613 | LHS, RHS, Loc, CompLHSTy, |
| 9614 | /*AllowBothBool*/getLangOpts().AltiVec, |
| 9615 | /*AllowBoolConversions*/getLangOpts().ZVector); |
| 9616 | if (CompLHSTy) *CompLHSTy = compType; |
| 9617 | return compType; |
| 9618 | } |
| 9619 | |
| 9620 | QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); |
| 9621 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 9622 | return QualType(); |
| 9623 | |
| 9624 | // Enforce type constraints: C99 6.5.6p3. |
| 9625 | |
| 9626 | // Handle the common case first (both operands are arithmetic). |
| 9627 | if (!compType.isNull() && compType->isArithmeticType()) { |
| 9628 | if (CompLHSTy) *CompLHSTy = compType; |
| 9629 | return compType; |
| 9630 | } |
| 9631 | |
| 9632 | // Either ptr - int or ptr - ptr. |
| 9633 | if (LHS.get()->getType()->isAnyPointerType()) { |
| 9634 | QualType lpointee = LHS.get()->getType()->getPointeeType(); |
| 9635 | |
| 9636 | // Diagnose bad cases where we step over interface counts. |
| 9637 | if (LHS.get()->getType()->isObjCObjectPointerType() && |
| 9638 | checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) |
| 9639 | return QualType(); |
| 9640 | |
| 9641 | // The result type of a pointer-int computation is the pointer type. |
| 9642 | if (RHS.get()->getType()->isIntegerType()) { |
| 9643 | // Subtracting from a null pointer should produce a warning. |
| 9644 | // The last argument to the diagnose call says this doesn't match the |
| 9645 | // GNU int-to-pointer idiom. |
| 9646 | if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, |
| 9647 | Expr::NPC_ValueDependentIsNotNull)) { |
| 9648 | // In C++ adding zero to a null pointer is defined. |
| 9649 | Expr::EvalResult KnownVal; |
| 9650 | if (!getLangOpts().CPlusPlus || |
| 9651 | (!RHS.get()->isValueDependent() && |
| 9652 | (!RHS.get()->EvaluateAsInt(KnownVal, Context) || |
| 9653 | KnownVal.Val.getInt() != 0))) { |
| 9654 | diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); |
| 9655 | } |
| 9656 | } |
| 9657 | |
| 9658 | if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) |
| 9659 | return QualType(); |
| 9660 | |
| 9661 | // Check array bounds for pointer arithemtic |
| 9662 | CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, |
| 9663 | /*AllowOnePastEnd*/true, /*IndexNegated*/true); |
| 9664 | |
| 9665 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
| 9666 | return LHS.get()->getType(); |
| 9667 | } |
| 9668 | |
| 9669 | // Handle pointer-pointer subtractions. |
| 9670 | if (const PointerType *RHSPTy |
| 9671 | = RHS.get()->getType()->getAs<PointerType>()) { |
| 9672 | QualType rpointee = RHSPTy->getPointeeType(); |
| 9673 | |
| 9674 | if (getLangOpts().CPlusPlus) { |
| 9675 | // Pointee types must be the same: C++ [expr.add] |
| 9676 | if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { |
| 9677 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); |
| 9678 | } |
| 9679 | } else { |
| 9680 | // Pointee types must be compatible C99 6.5.6p3 |
| 9681 | if (!Context.typesAreCompatible( |
| 9682 | Context.getCanonicalType(lpointee).getUnqualifiedType(), |
| 9683 | Context.getCanonicalType(rpointee).getUnqualifiedType())) { |
| 9684 | diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); |
| 9685 | return QualType(); |
| 9686 | } |
| 9687 | } |
| 9688 | |
| 9689 | if (!checkArithmeticBinOpPointerOperands(*this, Loc, |
| 9690 | LHS.get(), RHS.get())) |
| 9691 | return QualType(); |
| 9692 | |
| 9693 | // FIXME: Add warnings for nullptr - ptr. |
| 9694 | |
| 9695 | // The pointee type may have zero size. As an extension, a structure or |
| 9696 | // union may have zero size or an array may have zero length. In this |
| 9697 | // case subtraction does not make sense. |
| 9698 | if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { |
| 9699 | CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); |
| 9700 | if (ElementSize.isZero()) { |
| 9701 | Diag(Loc,diag::warn_sub_ptr_zero_size_types) |
| 9702 | << rpointee.getUnqualifiedType() |
| 9703 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9704 | } |
| 9705 | } |
| 9706 | |
| 9707 | if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); |
| 9708 | return Context.getPointerDiffType(); |
| 9709 | } |
| 9710 | } |
| 9711 | |
| 9712 | return InvalidOperands(Loc, LHS, RHS); |
| 9713 | } |
| 9714 | |
| 9715 | static bool isScopedEnumerationType(QualType T) { |
| 9716 | if (const EnumType *ET = T->getAs<EnumType>()) |
| 9717 | return ET->getDecl()->isScoped(); |
| 9718 | return false; |
| 9719 | } |
| 9720 | |
| 9721 | static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, |
| 9722 | SourceLocation Loc, BinaryOperatorKind Opc, |
| 9723 | QualType LHSType) { |
| 9724 | // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), |
| 9725 | // so skip remaining warnings as we don't want to modify values within Sema. |
| 9726 | if (S.getLangOpts().OpenCL) |
| 9727 | return; |
| 9728 | |
| 9729 | // Check right/shifter operand |
| 9730 | Expr::EvalResult RHSResult; |
| 9731 | if (RHS.get()->isValueDependent() || |
| 9732 | !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) |
| 9733 | return; |
| 9734 | llvm::APSInt Right = RHSResult.Val.getInt(); |
| 9735 | |
| 9736 | if (Right.isNegative()) { |
| 9737 | S.DiagRuntimeBehavior(Loc, RHS.get(), |
| 9738 | S.PDiag(diag::warn_shift_negative) |
| 9739 | << RHS.get()->getSourceRange()); |
| 9740 | return; |
| 9741 | } |
| 9742 | llvm::APInt LeftBits(Right.getBitWidth(), |
| 9743 | S.Context.getTypeSize(LHS.get()->getType())); |
| 9744 | if (Right.uge(LeftBits)) { |
| 9745 | S.DiagRuntimeBehavior(Loc, RHS.get(), |
| 9746 | S.PDiag(diag::warn_shift_gt_typewidth) |
| 9747 | << RHS.get()->getSourceRange()); |
| 9748 | return; |
| 9749 | } |
| 9750 | if (Opc != BO_Shl) |
| 9751 | return; |
| 9752 | |
| 9753 | // When left shifting an ICE which is signed, we can check for overflow which |
| 9754 | // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned |
| 9755 | // integers have defined behavior modulo one more than the maximum value |
| 9756 | // representable in the result type, so never warn for those. |
| 9757 | Expr::EvalResult LHSResult; |
| 9758 | if (LHS.get()->isValueDependent() || |
| 9759 | LHSType->hasUnsignedIntegerRepresentation() || |
| 9760 | !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) |
| 9761 | return; |
| 9762 | llvm::APSInt Left = LHSResult.Val.getInt(); |
| 9763 | |
| 9764 | // If LHS does not have a signed type and non-negative value |
| 9765 | // then, the behavior is undefined. Warn about it. |
| 9766 | if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { |
| 9767 | S.DiagRuntimeBehavior(Loc, LHS.get(), |
| 9768 | S.PDiag(diag::warn_shift_lhs_negative) |
| 9769 | << LHS.get()->getSourceRange()); |
| 9770 | return; |
| 9771 | } |
| 9772 | |
| 9773 | llvm::APInt ResultBits = |
| 9774 | static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); |
| 9775 | if (LeftBits.uge(ResultBits)) |
| 9776 | return; |
| 9777 | llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); |
| 9778 | Result = Result.shl(Right); |
| 9779 | |
| 9780 | // Print the bit representation of the signed integer as an unsigned |
| 9781 | // hexadecimal number. |
| 9782 | SmallString<40> HexResult; |
| 9783 | Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); |
| 9784 | |
| 9785 | // If we are only missing a sign bit, this is less likely to result in actual |
| 9786 | // bugs -- if the result is cast back to an unsigned type, it will have the |
| 9787 | // expected value. Thus we place this behind a different warning that can be |
| 9788 | // turned off separately if needed. |
| 9789 | if (LeftBits == ResultBits - 1) { |
| 9790 | S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) |
| 9791 | << HexResult << LHSType |
| 9792 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9793 | return; |
| 9794 | } |
| 9795 | |
| 9796 | S.Diag(Loc, diag::warn_shift_result_gt_typewidth) |
| 9797 | << HexResult.str() << Result.getMinSignedBits() << LHSType |
| 9798 | << Left.getBitWidth() << LHS.get()->getSourceRange() |
| 9799 | << RHS.get()->getSourceRange(); |
| 9800 | } |
| 9801 | |
| 9802 | /// Return the resulting type when a vector is shifted |
| 9803 | /// by a scalar or vector shift amount. |
| 9804 | static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 9805 | SourceLocation Loc, bool IsCompAssign) { |
| 9806 | // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. |
| 9807 | if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && |
| 9808 | !LHS.get()->getType()->isVectorType()) { |
| 9809 | S.Diag(Loc, diag::err_shift_rhs_only_vector) |
| 9810 | << RHS.get()->getType() << LHS.get()->getType() |
| 9811 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9812 | return QualType(); |
| 9813 | } |
| 9814 | |
| 9815 | if (!IsCompAssign) { |
| 9816 | LHS = S.UsualUnaryConversions(LHS.get()); |
| 9817 | if (LHS.isInvalid()) return QualType(); |
| 9818 | } |
| 9819 | |
| 9820 | RHS = S.UsualUnaryConversions(RHS.get()); |
| 9821 | if (RHS.isInvalid()) return QualType(); |
| 9822 | |
| 9823 | QualType LHSType = LHS.get()->getType(); |
| 9824 | // Note that LHS might be a scalar because the routine calls not only in |
| 9825 | // OpenCL case. |
| 9826 | const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); |
| 9827 | QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; |
| 9828 | |
| 9829 | // Note that RHS might not be a vector. |
| 9830 | QualType RHSType = RHS.get()->getType(); |
| 9831 | const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); |
| 9832 | QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; |
| 9833 | |
| 9834 | // The operands need to be integers. |
| 9835 | if (!LHSEleType->isIntegerType()) { |
| 9836 | S.Diag(Loc, diag::err_typecheck_expect_int) |
| 9837 | << LHS.get()->getType() << LHS.get()->getSourceRange(); |
| 9838 | return QualType(); |
| 9839 | } |
| 9840 | |
| 9841 | if (!RHSEleType->isIntegerType()) { |
| 9842 | S.Diag(Loc, diag::err_typecheck_expect_int) |
| 9843 | << RHS.get()->getType() << RHS.get()->getSourceRange(); |
| 9844 | return QualType(); |
| 9845 | } |
| 9846 | |
| 9847 | if (!LHSVecTy) { |
| 9848 | assert(RHSVecTy); |
| 9849 | if (IsCompAssign) |
| 9850 | return RHSType; |
| 9851 | if (LHSEleType != RHSEleType) { |
| 9852 | LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); |
| 9853 | LHSEleType = RHSEleType; |
| 9854 | } |
| 9855 | QualType VecTy = |
| 9856 | S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); |
| 9857 | LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); |
| 9858 | LHSType = VecTy; |
| 9859 | } else if (RHSVecTy) { |
| 9860 | // OpenCL v1.1 s6.3.j says that for vector types, the operators |
| 9861 | // are applied component-wise. So if RHS is a vector, then ensure |
| 9862 | // that the number of elements is the same as LHS... |
| 9863 | if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { |
| 9864 | S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) |
| 9865 | << LHS.get()->getType() << RHS.get()->getType() |
| 9866 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9867 | return QualType(); |
| 9868 | } |
| 9869 | if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { |
| 9870 | const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); |
| 9871 | const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); |
| 9872 | if (LHSBT != RHSBT && |
| 9873 | S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { |
| 9874 | S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) |
| 9875 | << LHS.get()->getType() << RHS.get()->getType() |
| 9876 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9877 | } |
| 9878 | } |
| 9879 | } else { |
| 9880 | // ...else expand RHS to match the number of elements in LHS. |
| 9881 | QualType VecTy = |
| 9882 | S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); |
| 9883 | RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); |
| 9884 | } |
| 9885 | |
| 9886 | return LHSType; |
| 9887 | } |
| 9888 | |
| 9889 | // C99 6.5.7 |
| 9890 | QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, |
| 9891 | SourceLocation Loc, BinaryOperatorKind Opc, |
| 9892 | bool IsCompAssign) { |
| 9893 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); |
| 9894 | |
| 9895 | // Vector shifts promote their scalar inputs to vector type. |
| 9896 | if (LHS.get()->getType()->isVectorType() || |
| 9897 | RHS.get()->getType()->isVectorType()) { |
| 9898 | if (LangOpts.ZVector) { |
| 9899 | // The shift operators for the z vector extensions work basically |
| 9900 | // like general shifts, except that neither the LHS nor the RHS is |
| 9901 | // allowed to be a "vector bool". |
| 9902 | if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) |
| 9903 | if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) |
| 9904 | return InvalidOperands(Loc, LHS, RHS); |
| 9905 | if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) |
| 9906 | if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) |
| 9907 | return InvalidOperands(Loc, LHS, RHS); |
| 9908 | } |
| 9909 | return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); |
| 9910 | } |
| 9911 | |
| 9912 | // Shifts don't perform usual arithmetic conversions, they just do integer |
| 9913 | // promotions on each operand. C99 6.5.7p3 |
| 9914 | |
| 9915 | // For the LHS, do usual unary conversions, but then reset them away |
| 9916 | // if this is a compound assignment. |
| 9917 | ExprResult OldLHS = LHS; |
| 9918 | LHS = UsualUnaryConversions(LHS.get()); |
| 9919 | if (LHS.isInvalid()) |
| 9920 | return QualType(); |
| 9921 | QualType LHSType = LHS.get()->getType(); |
| 9922 | if (IsCompAssign) LHS = OldLHS; |
| 9923 | |
| 9924 | // The RHS is simpler. |
| 9925 | RHS = UsualUnaryConversions(RHS.get()); |
| 9926 | if (RHS.isInvalid()) |
| 9927 | return QualType(); |
| 9928 | QualType RHSType = RHS.get()->getType(); |
| 9929 | |
| 9930 | // C99 6.5.7p2: Each of the operands shall have integer type. |
| 9931 | if (!LHSType->hasIntegerRepresentation() || |
| 9932 | !RHSType->hasIntegerRepresentation()) |
| 9933 | return InvalidOperands(Loc, LHS, RHS); |
| 9934 | |
| 9935 | // C++0x: Don't allow scoped enums. FIXME: Use something better than |
| 9936 | // hasIntegerRepresentation() above instead of this. |
| 9937 | if (isScopedEnumerationType(LHSType) || |
| 9938 | isScopedEnumerationType(RHSType)) { |
| 9939 | return InvalidOperands(Loc, LHS, RHS); |
| 9940 | } |
| 9941 | // Sanity-check shift operands |
| 9942 | DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); |
| 9943 | |
| 9944 | // In CHERI offset mode shifts only look at the offset and ignore the base. |
| 9945 | // This is rarely the intended behaviour so warn if that is the case. |
| 9946 | if (getLangOpts().cheriUIntCapUsesOffset() && |
| 9947 | (LHSType->isIntCapType() || RHSType->isIntCapType()) && |
| 9948 | (Opc == BO_Shl || Opc == BO_ShlAssign || Opc == BO_Shr || |
| 9949 | Opc == BO_ShrAssign)) |
| 9950 | DiagRuntimeBehavior(Loc, RHS.get(), |
| 9951 | PDiag(diag::warn_uintcap_bad_bitwise_op) |
| 9952 | << 1 /*=shift*/ << 0 /* usecase is hashing */ |
| 9953 | << LHS.get()->getSourceRange() |
| 9954 | << RHS.get()->getSourceRange()); |
| 9955 | |
| 9956 | // "The type of the result is that of the promoted left operand." |
| 9957 | return LHSType; |
| 9958 | } |
| 9959 | |
| 9960 | /// If two different enums are compared, raise a warning. |
| 9961 | static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, |
| 9962 | Expr *RHS) { |
| 9963 | QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); |
| 9964 | QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); |
| 9965 | |
| 9966 | const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); |
| 9967 | if (!LHSEnumType) |
| 9968 | return; |
| 9969 | const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); |
| 9970 | if (!RHSEnumType) |
| 9971 | return; |
| 9972 | |
| 9973 | // Ignore anonymous enums. |
| 9974 | if (!LHSEnumType->getDecl()->getIdentifier() && |
| 9975 | !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) |
| 9976 | return; |
| 9977 | if (!RHSEnumType->getDecl()->getIdentifier() && |
| 9978 | !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) |
| 9979 | return; |
| 9980 | |
| 9981 | if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) |
| 9982 | return; |
| 9983 | |
| 9984 | S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) |
| 9985 | << LHSStrippedType << RHSStrippedType |
| 9986 | << LHS->getSourceRange() << RHS->getSourceRange(); |
| 9987 | } |
| 9988 | |
| 9989 | /// Diagnose bad pointer comparisons. |
| 9990 | static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, |
| 9991 | ExprResult &LHS, ExprResult &RHS, |
| 9992 | bool IsError) { |
| 9993 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers |
| 9994 | : diag::ext_typecheck_comparison_of_distinct_pointers) |
| 9995 | << LHS.get()->getType() << RHS.get()->getType() |
| 9996 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 9997 | } |
| 9998 | |
| 9999 | /// Returns false if the pointers are converted to a composite type, |
| 10000 | /// true otherwise. |
| 10001 | static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, |
| 10002 | ExprResult &LHS, ExprResult &RHS) { |
| 10003 | // C++ [expr.rel]p2: |
| 10004 | // [...] Pointer conversions (4.10) and qualification |
| 10005 | // conversions (4.4) are performed on pointer operands (or on |
| 10006 | // a pointer operand and a null pointer constant) to bring |
| 10007 | // them to their composite pointer type. [...] |
| 10008 | // |
| 10009 | // C++ [expr.eq]p1 uses the same notion for (in)equality |
| 10010 | // comparisons of pointers. |
| 10011 | |
| 10012 | QualType LHSType = LHS.get()->getType(); |
| 10013 | QualType RHSType = RHS.get()->getType(); |
| 10014 | assert(LHSType->isPointerType() || RHSType->isPointerType() || |
| 10015 | LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); |
| 10016 | |
| 10017 | QualType T = S.FindCompositePointerType(Loc, LHS, RHS); |
| 10018 | if (T.isNull()) { |
| 10019 | if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && |
| 10020 | (RHSType->isPointerType() || RHSType->isMemberPointerType())) |
| 10021 | diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); |
| 10022 | else |
| 10023 | S.InvalidOperands(Loc, LHS, RHS); |
| 10024 | return true; |
| 10025 | } |
| 10026 | |
| 10027 | LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); |
| 10028 | RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); |
| 10029 | return false; |
| 10030 | } |
| 10031 | |
| 10032 | static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, |
| 10033 | ExprResult &LHS, |
| 10034 | ExprResult &RHS, |
| 10035 | bool IsError) { |
| 10036 | S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void |
| 10037 | : diag::ext_typecheck_comparison_of_fptr_to_void) |
| 10038 | << LHS.get()->getType() << RHS.get()->getType() |
| 10039 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 10040 | } |
| 10041 | |
| 10042 | static bool isObjCObjectLiteral(ExprResult &E) { |
| 10043 | switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { |
| 10044 | case Stmt::ObjCArrayLiteralClass: |
| 10045 | case Stmt::ObjCDictionaryLiteralClass: |
| 10046 | case Stmt::ObjCStringLiteralClass: |
| 10047 | case Stmt::ObjCBoxedExprClass: |
| 10048 | return true; |
| 10049 | default: |
| 10050 | // Note that ObjCBoolLiteral is NOT an object literal! |
| 10051 | return false; |
| 10052 | } |
| 10053 | } |
| 10054 | |
| 10055 | static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { |
| 10056 | const ObjCObjectPointerType *Type = |
| 10057 | LHS->getType()->getAs<ObjCObjectPointerType>(); |
| 10058 | |
| 10059 | // If this is not actually an Objective-C object, bail out. |
| 10060 | if (!Type) |
| 10061 | return false; |
| 10062 | |
| 10063 | // Get the LHS object's interface type. |
| 10064 | QualType InterfaceType = Type->getPointeeType(); |
| 10065 | |
| 10066 | // If the RHS isn't an Objective-C object, bail out. |
| 10067 | if (!RHS->getType()->isObjCObjectPointerType()) |
| 10068 | return false; |
| 10069 | |
| 10070 | // Try to find the -isEqual: method. |
| 10071 | Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); |
| 10072 | ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, |
| 10073 | InterfaceType, |
| 10074 | /*instance=*/true); |
| 10075 | if (!Method) { |
| 10076 | if (Type->isObjCIdType()) { |
| 10077 | // For 'id', just check the global pool. |
| 10078 | Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), |
| 10079 | /*receiverId=*/true); |
| 10080 | } else { |
| 10081 | // Check protocols. |
| 10082 | Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, |
| 10083 | /*instance=*/true); |
| 10084 | } |
| 10085 | } |
| 10086 | |
| 10087 | if (!Method) |
| 10088 | return false; |
| 10089 | |
| 10090 | QualType T = Method->parameters()[0]->getType(); |
| 10091 | if (!T->isObjCObjectPointerType()) |
| 10092 | return false; |
| 10093 | |
| 10094 | QualType R = Method->getReturnType(); |
| 10095 | if (!R->isScalarType()) |
| 10096 | return false; |
| 10097 | |
| 10098 | return true; |
| 10099 | } |
| 10100 | |
| 10101 | Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { |
| 10102 | FromE = FromE->IgnoreParenImpCasts(); |
| 10103 | switch (FromE->getStmtClass()) { |
| 10104 | default: |
| 10105 | break; |
| 10106 | case Stmt::ObjCStringLiteralClass: |
| 10107 | // "string literal" |
| 10108 | return LK_String; |
| 10109 | case Stmt::ObjCArrayLiteralClass: |
| 10110 | // "array literal" |
| 10111 | return LK_Array; |
| 10112 | case Stmt::ObjCDictionaryLiteralClass: |
| 10113 | // "dictionary literal" |
| 10114 | return LK_Dictionary; |
| 10115 | case Stmt::BlockExprClass: |
| 10116 | return LK_Block; |
| 10117 | case Stmt::ObjCBoxedExprClass: { |
| 10118 | Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); |
| 10119 | switch (Inner->getStmtClass()) { |
| 10120 | case Stmt::IntegerLiteralClass: |
| 10121 | case Stmt::FloatingLiteralClass: |
| 10122 | case Stmt::CharacterLiteralClass: |
| 10123 | case Stmt::ObjCBoolLiteralExprClass: |
| 10124 | case Stmt::CXXBoolLiteralExprClass: |
| 10125 | // "numeric literal" |
| 10126 | return LK_Numeric; |
| 10127 | case Stmt::ImplicitCastExprClass: { |
| 10128 | CastKind CK = cast<CastExpr>(Inner)->getCastKind(); |
| 10129 | // Boolean literals can be represented by implicit casts. |
| 10130 | if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) |
| 10131 | return LK_Numeric; |
| 10132 | break; |
| 10133 | } |
| 10134 | default: |
| 10135 | break; |
| 10136 | } |
| 10137 | return LK_Boxed; |
| 10138 | } |
| 10139 | } |
| 10140 | return LK_None; |
| 10141 | } |
| 10142 | |
| 10143 | static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, |
| 10144 | ExprResult &LHS, ExprResult &RHS, |
| 10145 | BinaryOperator::Opcode Opc){ |
| 10146 | Expr *Literal; |
| 10147 | Expr *Other; |
| 10148 | if (isObjCObjectLiteral(LHS)) { |
| 10149 | Literal = LHS.get(); |
| 10150 | Other = RHS.get(); |
| 10151 | } else { |
| 10152 | Literal = RHS.get(); |
| 10153 | Other = LHS.get(); |
| 10154 | } |
| 10155 | |
| 10156 | // Don't warn on comparisons against nil. |
| 10157 | Other = Other->IgnoreParenCasts(); |
| 10158 | if (Other->isNullPointerConstant(S.getASTContext(), |
| 10159 | Expr::NPC_ValueDependentIsNotNull)) |
| 10160 | return; |
| 10161 | |
| 10162 | // This should be kept in sync with warn_objc_literal_comparison. |
| 10163 | // LK_String should always be after the other literals, since it has its own |
| 10164 | // warning flag. |
| 10165 | Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); |
| 10166 | assert(LiteralKind != Sema::LK_Block); |
| 10167 | if (LiteralKind == Sema::LK_None) { |
| 10168 | llvm_unreachable("Unknown Objective-C object literal kind" ); |
| 10169 | } |
| 10170 | |
| 10171 | if (LiteralKind == Sema::LK_String) |
| 10172 | S.Diag(Loc, diag::warn_objc_string_literal_comparison) |
| 10173 | << Literal->getSourceRange(); |
| 10174 | else |
| 10175 | S.Diag(Loc, diag::warn_objc_literal_comparison) |
| 10176 | << LiteralKind << Literal->getSourceRange(); |
| 10177 | |
| 10178 | if (BinaryOperator::isEqualityOp(Opc) && |
| 10179 | hasIsEqualMethod(S, LHS.get(), RHS.get())) { |
| 10180 | SourceLocation Start = LHS.get()->getBeginLoc(); |
| 10181 | SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); |
| 10182 | CharSourceRange OpRange = |
| 10183 | CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); |
| 10184 | |
| 10185 | S.Diag(Loc, diag::note_objc_literal_comparison_isequal) |
| 10186 | << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![" ) |
| 10187 | << FixItHint::CreateReplacement(OpRange, " isEqual:" ) |
| 10188 | << FixItHint::CreateInsertion(End, "]" ); |
| 10189 | } |
| 10190 | } |
| 10191 | |
| 10192 | /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. |
| 10193 | static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, |
| 10194 | ExprResult &RHS, SourceLocation Loc, |
| 10195 | BinaryOperatorKind Opc) { |
| 10196 | // Check that left hand side is !something. |
| 10197 | UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); |
| 10198 | if (!UO || UO->getOpcode() != UO_LNot) return; |
| 10199 | |
| 10200 | // Only check if the right hand side is non-bool arithmetic type. |
| 10201 | if (RHS.get()->isKnownToHaveBooleanValue()) return; |
| 10202 | |
| 10203 | // Make sure that the something in !something is not bool. |
| 10204 | Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); |
| 10205 | if (SubExpr->isKnownToHaveBooleanValue()) return; |
| 10206 | |
| 10207 | // Emit warning. |
| 10208 | bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; |
| 10209 | S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) |
| 10210 | << Loc << IsBitwiseOp; |
| 10211 | |
| 10212 | // First note suggest !(x < y) |
| 10213 | SourceLocation FirstOpen = SubExpr->getBeginLoc(); |
| 10214 | SourceLocation FirstClose = RHS.get()->getEndLoc(); |
| 10215 | FirstClose = S.getLocForEndOfToken(FirstClose); |
| 10216 | if (FirstClose.isInvalid()) |
| 10217 | FirstOpen = SourceLocation(); |
| 10218 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) |
| 10219 | << IsBitwiseOp |
| 10220 | << FixItHint::CreateInsertion(FirstOpen, "(" ) |
| 10221 | << FixItHint::CreateInsertion(FirstClose, ")" ); |
| 10222 | |
| 10223 | // Second note suggests (!x) < y |
| 10224 | SourceLocation SecondOpen = LHS.get()->getBeginLoc(); |
| 10225 | SourceLocation SecondClose = LHS.get()->getEndLoc(); |
| 10226 | SecondClose = S.getLocForEndOfToken(SecondClose); |
| 10227 | if (SecondClose.isInvalid()) |
| 10228 | SecondOpen = SourceLocation(); |
| 10229 | S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) |
| 10230 | << FixItHint::CreateInsertion(SecondOpen, "(" ) |
| 10231 | << FixItHint::CreateInsertion(SecondClose, ")" ); |
| 10232 | } |
| 10233 | |
| 10234 | // Get the decl for a simple expression: a reference to a variable, |
| 10235 | // an implicit C++ field reference, or an implicit ObjC ivar reference. |
| 10236 | static ValueDecl *getCompareDecl(Expr *E) { |
| 10237 | if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) |
| 10238 | return DR->getDecl(); |
| 10239 | if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { |
| 10240 | if (Ivar->isFreeIvar()) |
| 10241 | return Ivar->getDecl(); |
| 10242 | } |
| 10243 | if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { |
| 10244 | if (Mem->isImplicitAccess()) |
| 10245 | return Mem->getMemberDecl(); |
| 10246 | } |
| 10247 | return nullptr; |
| 10248 | } |
| 10249 | |
| 10250 | /// Diagnose some forms of syntactically-obvious tautological comparison. |
| 10251 | static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, |
| 10252 | Expr *LHS, Expr *RHS, |
| 10253 | BinaryOperatorKind Opc) { |
| 10254 | Expr *LHSStripped = LHS->IgnoreParenImpCasts(); |
| 10255 | Expr *RHSStripped = RHS->IgnoreParenImpCasts(); |
| 10256 | |
| 10257 | QualType LHSType = LHS->getType(); |
| 10258 | QualType RHSType = RHS->getType(); |
| 10259 | if (LHSType->hasFloatingRepresentation() || |
| 10260 | (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || |
| 10261 | LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || |
| 10262 | S.inTemplateInstantiation()) |
| 10263 | return; |
| 10264 | |
| 10265 | // Comparisons between two array types are ill-formed for operator<=>, so |
| 10266 | // we shouldn't emit any additional warnings about it. |
| 10267 | if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) |
| 10268 | return; |
| 10269 | |
| 10270 | // For non-floating point types, check for self-comparisons of the form |
| 10271 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
| 10272 | // often indicate logic errors in the program. |
| 10273 | // |
| 10274 | // NOTE: Don't warn about comparison expressions resulting from macro |
| 10275 | // expansion. Also don't warn about comparisons which are only self |
| 10276 | // comparisons within a template instantiation. The warnings should catch |
| 10277 | // obvious cases in the definition of the template anyways. The idea is to |
| 10278 | // warn when the typed comparison operator will always evaluate to the same |
| 10279 | // result. |
| 10280 | ValueDecl *DL = getCompareDecl(LHSStripped); |
| 10281 | ValueDecl *DR = getCompareDecl(RHSStripped); |
| 10282 | if (DL && DR && declaresSameEntity(DL, DR)) { |
| 10283 | StringRef Result; |
| 10284 | switch (Opc) { |
| 10285 | case BO_EQ: case BO_LE: case BO_GE: |
| 10286 | Result = "true" ; |
| 10287 | break; |
| 10288 | case BO_NE: case BO_LT: case BO_GT: |
| 10289 | Result = "false" ; |
| 10290 | break; |
| 10291 | case BO_Cmp: |
| 10292 | Result = "'std::strong_ordering::equal'" ; |
| 10293 | break; |
| 10294 | default: |
| 10295 | break; |
| 10296 | } |
| 10297 | S.DiagRuntimeBehavior(Loc, nullptr, |
| 10298 | S.PDiag(diag::warn_comparison_always) |
| 10299 | << 0 /*self-comparison*/ << !Result.empty() |
| 10300 | << Result); |
| 10301 | } else if (DL && DR && |
| 10302 | DL->getType()->isArrayType() && DR->getType()->isArrayType() && |
| 10303 | !DL->isWeak() && !DR->isWeak()) { |
| 10304 | // What is it always going to evaluate to? |
| 10305 | StringRef Result; |
| 10306 | switch(Opc) { |
| 10307 | case BO_EQ: // e.g. array1 == array2 |
| 10308 | Result = "false" ; |
| 10309 | break; |
| 10310 | case BO_NE: // e.g. array1 != array2 |
| 10311 | Result = "true" ; |
| 10312 | break; |
| 10313 | default: // e.g. array1 <= array2 |
| 10314 | // The best we can say is 'a constant' |
| 10315 | break; |
| 10316 | } |
| 10317 | S.DiagRuntimeBehavior(Loc, nullptr, |
| 10318 | S.PDiag(diag::warn_comparison_always) |
| 10319 | << 1 /*array comparison*/ |
| 10320 | << !Result.empty() << Result); |
| 10321 | } |
| 10322 | |
| 10323 | if (isa<CastExpr>(LHSStripped)) |
| 10324 | LHSStripped = LHSStripped->IgnoreParenCasts(); |
| 10325 | if (isa<CastExpr>(RHSStripped)) |
| 10326 | RHSStripped = RHSStripped->IgnoreParenCasts(); |
| 10327 | |
| 10328 | // Warn about comparisons against a string constant (unless the other |
| 10329 | // operand is null); the user probably wants strcmp. |
| 10330 | Expr *LiteralString = nullptr; |
| 10331 | Expr *LiteralStringStripped = nullptr; |
| 10332 | if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && |
| 10333 | !RHSStripped->isNullPointerConstant(S.Context, |
| 10334 | Expr::NPC_ValueDependentIsNull)) { |
| 10335 | LiteralString = LHS; |
| 10336 | LiteralStringStripped = LHSStripped; |
| 10337 | } else if ((isa<StringLiteral>(RHSStripped) || |
| 10338 | isa<ObjCEncodeExpr>(RHSStripped)) && |
| 10339 | !LHSStripped->isNullPointerConstant(S.Context, |
| 10340 | Expr::NPC_ValueDependentIsNull)) { |
| 10341 | LiteralString = RHS; |
| 10342 | LiteralStringStripped = RHSStripped; |
| 10343 | } |
| 10344 | |
| 10345 | if (LiteralString) { |
| 10346 | S.DiagRuntimeBehavior(Loc, nullptr, |
| 10347 | S.PDiag(diag::warn_stringcompare) |
| 10348 | << isa<ObjCEncodeExpr>(LiteralStringStripped) |
| 10349 | << LiteralString->getSourceRange()); |
| 10350 | } |
| 10351 | } |
| 10352 | |
| 10353 | static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { |
| 10354 | switch (CK) { |
| 10355 | default: { |
| 10356 | #ifndef NDEBUG |
| 10357 | llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) |
| 10358 | << "\n" ; |
| 10359 | #endif |
| 10360 | llvm_unreachable("unhandled cast kind" ); |
| 10361 | } |
| 10362 | case CK_UserDefinedConversion: |
| 10363 | return ICK_Identity; |
| 10364 | case CK_LValueToRValue: |
| 10365 | return ICK_Lvalue_To_Rvalue; |
| 10366 | case CK_ArrayToPointerDecay: |
| 10367 | return ICK_Array_To_Pointer; |
| 10368 | case CK_FunctionToPointerDecay: |
| 10369 | return ICK_Function_To_Pointer; |
| 10370 | case CK_IntegralCast: |
| 10371 | return ICK_Integral_Conversion; |
| 10372 | case CK_FloatingCast: |
| 10373 | return ICK_Floating_Conversion; |
| 10374 | case CK_IntegralToFloating: |
| 10375 | case CK_FloatingToIntegral: |
| 10376 | return ICK_Floating_Integral; |
| 10377 | case CK_IntegralComplexCast: |
| 10378 | case CK_FloatingComplexCast: |
| 10379 | case CK_FloatingComplexToIntegralComplex: |
| 10380 | case CK_IntegralComplexToFloatingComplex: |
| 10381 | return ICK_Complex_Conversion; |
| 10382 | case CK_FloatingComplexToReal: |
| 10383 | case CK_FloatingRealToComplex: |
| 10384 | case CK_IntegralComplexToReal: |
| 10385 | case CK_IntegralRealToComplex: |
| 10386 | return ICK_Complex_Real; |
| 10387 | } |
| 10388 | } |
| 10389 | |
| 10390 | static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, |
| 10391 | QualType FromType, |
| 10392 | SourceLocation Loc) { |
| 10393 | // Check for a narrowing implicit conversion. |
| 10394 | StandardConversionSequence SCS; |
| 10395 | SCS.setAsIdentityConversion(); |
| 10396 | SCS.setToType(0, FromType); |
| 10397 | SCS.setToType(1, ToType); |
| 10398 | if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) |
| 10399 | SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); |
| 10400 | |
| 10401 | APValue PreNarrowingValue; |
| 10402 | QualType PreNarrowingType; |
| 10403 | switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, |
| 10404 | PreNarrowingType, |
| 10405 | /*IgnoreFloatToIntegralConversion*/ true)) { |
| 10406 | case NK_Dependent_Narrowing: |
| 10407 | // Implicit conversion to a narrower type, but the expression is |
| 10408 | // value-dependent so we can't tell whether it's actually narrowing. |
| 10409 | case NK_Not_Narrowing: |
| 10410 | return false; |
| 10411 | |
| 10412 | case NK_Constant_Narrowing: |
| 10413 | // Implicit conversion to a narrower type, and the value is not a constant |
| 10414 | // expression. |
| 10415 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) |
| 10416 | << /*Constant*/ 1 |
| 10417 | << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; |
| 10418 | return true; |
| 10419 | |
| 10420 | case NK_Variable_Narrowing: |
| 10421 | // Implicit conversion to a narrower type, and the value is not a constant |
| 10422 | // expression. |
| 10423 | case NK_Type_Narrowing: |
| 10424 | S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) |
| 10425 | << /*Constant*/ 0 << FromType << ToType; |
| 10426 | // TODO: It's not a constant expression, but what if the user intended it |
| 10427 | // to be? Can we produce notes to help them figure out why it isn't? |
| 10428 | return true; |
| 10429 | } |
| 10430 | llvm_unreachable("unhandled case in switch" ); |
| 10431 | } |
| 10432 | |
| 10433 | static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, |
| 10434 | ExprResult &LHS, |
| 10435 | ExprResult &RHS, |
| 10436 | SourceLocation Loc) { |
| 10437 | using CCT = ComparisonCategoryType; |
| 10438 | |
| 10439 | QualType LHSType = LHS.get()->getType(); |
| 10440 | QualType RHSType = RHS.get()->getType(); |
| 10441 | // Dig out the original argument type and expression before implicit casts |
| 10442 | // were applied. These are the types/expressions we need to check the |
| 10443 | // [expr.spaceship] requirements against. |
| 10444 | ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); |
| 10445 | ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); |
| 10446 | QualType LHSStrippedType = LHSStripped.get()->getType(); |
| 10447 | QualType RHSStrippedType = RHSStripped.get()->getType(); |
| 10448 | |
| 10449 | // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the |
| 10450 | // other is not, the program is ill-formed. |
| 10451 | if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { |
| 10452 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); |
| 10453 | return QualType(); |
| 10454 | } |
| 10455 | |
| 10456 | int = (int)LHSStrippedType->isEnumeralType() + |
| 10457 | RHSStrippedType->isEnumeralType(); |
| 10458 | if (NumEnumArgs == 1) { |
| 10459 | bool LHSIsEnum = LHSStrippedType->isEnumeralType(); |
| 10460 | QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; |
| 10461 | if (OtherTy->hasFloatingRepresentation()) { |
| 10462 | S.InvalidOperands(Loc, LHSStripped, RHSStripped); |
| 10463 | return QualType(); |
| 10464 | } |
| 10465 | } |
| 10466 | if (NumEnumArgs == 2) { |
| 10467 | // C++2a [expr.spaceship]p5: If both operands have the same enumeration |
| 10468 | // type E, the operator yields the result of converting the operands |
| 10469 | // to the underlying type of E and applying <=> to the converted operands. |
| 10470 | if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { |
| 10471 | S.InvalidOperands(Loc, LHS, RHS); |
| 10472 | return QualType(); |
| 10473 | } |
| 10474 | QualType IntType = |
| 10475 | LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); |
| 10476 | assert(IntType->isArithmeticType()); |
| 10477 | |
| 10478 | // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we |
| 10479 | // promote the boolean type, and all other promotable integer types, to |
| 10480 | // avoid this. |
| 10481 | if (IntType->isPromotableIntegerType()) |
| 10482 | IntType = S.Context.getPromotedIntegerType(IntType); |
| 10483 | |
| 10484 | LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); |
| 10485 | RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); |
| 10486 | LHSType = RHSType = IntType; |
| 10487 | } |
| 10488 | |
| 10489 | // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the |
| 10490 | // usual arithmetic conversions are applied to the operands. |
| 10491 | QualType Type = S.UsualArithmeticConversions(LHS, RHS); |
| 10492 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 10493 | return QualType(); |
| 10494 | if (Type.isNull()) |
| 10495 | return S.InvalidOperands(Loc, LHS, RHS); |
| 10496 | assert(Type->isArithmeticType() || Type->isEnumeralType()); |
| 10497 | |
| 10498 | bool HasNarrowing = checkThreeWayNarrowingConversion( |
| 10499 | S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); |
| 10500 | HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, |
| 10501 | RHS.get()->getBeginLoc()); |
| 10502 | if (HasNarrowing) |
| 10503 | return QualType(); |
| 10504 | |
| 10505 | assert(!Type.isNull() && "composite type for <=> has not been set" ); |
| 10506 | |
| 10507 | auto TypeKind = [&]() { |
| 10508 | if (const ComplexType *CT = Type->getAs<ComplexType>()) { |
| 10509 | if (CT->getElementType()->hasFloatingRepresentation()) |
| 10510 | return CCT::WeakEquality; |
| 10511 | return CCT::StrongEquality; |
| 10512 | } |
| 10513 | if (Type->isIntegralOrEnumerationType()) |
| 10514 | return CCT::StrongOrdering; |
| 10515 | if (Type->hasFloatingRepresentation()) |
| 10516 | return CCT::PartialOrdering; |
| 10517 | llvm_unreachable("other types are unimplemented" ); |
| 10518 | }(); |
| 10519 | |
| 10520 | return S.CheckComparisonCategoryType(TypeKind, Loc); |
| 10521 | } |
| 10522 | |
| 10523 | static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, |
| 10524 | ExprResult &RHS, |
| 10525 | SourceLocation Loc, |
| 10526 | BinaryOperatorKind Opc) { |
| 10527 | if (Opc == BO_Cmp) |
| 10528 | return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); |
| 10529 | |
| 10530 | // C99 6.5.8p3 / C99 6.5.9p4 |
| 10531 | QualType Type = S.UsualArithmeticConversions(LHS, RHS); |
| 10532 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 10533 | return QualType(); |
| 10534 | if (Type.isNull()) |
| 10535 | return S.InvalidOperands(Loc, LHS, RHS); |
| 10536 | assert(Type->isArithmeticType() || Type->isEnumeralType()); |
| 10537 | |
| 10538 | checkEnumComparison(S, Loc, LHS.get(), RHS.get()); |
| 10539 | |
| 10540 | if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) |
| 10541 | return S.InvalidOperands(Loc, LHS, RHS); |
| 10542 | |
| 10543 | // Check for comparisons of floating point operands using != and ==. |
| 10544 | if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) |
| 10545 | S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); |
| 10546 | |
| 10547 | // The result of comparisons is 'bool' in C++, 'int' in C. |
| 10548 | return S.Context.getLogicalOperationType(); |
| 10549 | } |
| 10550 | |
| 10551 | // C99 6.5.8, C++ [expr.rel] |
| 10552 | QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, |
| 10553 | SourceLocation Loc, |
| 10554 | BinaryOperatorKind Opc) { |
| 10555 | bool IsRelational = BinaryOperator::isRelationalOp(Opc); |
| 10556 | bool IsThreeWay = Opc == BO_Cmp; |
| 10557 | auto IsAnyPointerType = [](ExprResult E) { |
| 10558 | QualType Ty = E.get()->getType(); |
| 10559 | return Ty->isPointerType() || Ty->isMemberPointerType(); |
| 10560 | }; |
| 10561 | |
| 10562 | // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer |
| 10563 | // type, array-to-pointer, ..., conversions are performed on both operands to |
| 10564 | // bring them to their composite type. |
| 10565 | // Otherwise, all comparisons expect an rvalue, so convert to rvalue before |
| 10566 | // any type-related checks. |
| 10567 | if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { |
| 10568 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); |
| 10569 | if (LHS.isInvalid()) |
| 10570 | return QualType(); |
| 10571 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); |
| 10572 | if (RHS.isInvalid()) |
| 10573 | return QualType(); |
| 10574 | } else { |
| 10575 | LHS = DefaultLvalueConversion(LHS.get()); |
| 10576 | if (LHS.isInvalid()) |
| 10577 | return QualType(); |
| 10578 | RHS = DefaultLvalueConversion(RHS.get()); |
| 10579 | if (RHS.isInvalid()) |
| 10580 | return QualType(); |
| 10581 | } |
| 10582 | |
| 10583 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); |
| 10584 | |
| 10585 | // Handle vector comparisons separately. |
| 10586 | if (LHS.get()->getType()->isVectorType() || |
| 10587 | RHS.get()->getType()->isVectorType()) |
| 10588 | return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); |
| 10589 | |
| 10590 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); |
| 10591 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); |
| 10592 | |
| 10593 | QualType LHSType = LHS.get()->getType(); |
| 10594 | QualType RHSType = RHS.get()->getType(); |
| 10595 | if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && |
| 10596 | (RHSType->isArithmeticType() || RHSType->isEnumeralType())) |
| 10597 | return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); |
| 10598 | |
| 10599 | const Expr::NullPointerConstantKind LHSNullKind = |
| 10600 | LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); |
| 10601 | const Expr::NullPointerConstantKind RHSNullKind = |
| 10602 | RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); |
| 10603 | bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; |
| 10604 | bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; |
| 10605 | |
| 10606 | auto computeResultTy = [&]() { |
| 10607 | if (Opc != BO_Cmp) |
| 10608 | return Context.getLogicalOperationType(); |
| 10609 | assert(getLangOpts().CPlusPlus); |
| 10610 | assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); |
| 10611 | |
| 10612 | QualType CompositeTy = LHS.get()->getType(); |
| 10613 | assert(!CompositeTy->isReferenceType()); |
| 10614 | |
| 10615 | auto buildResultTy = [&](ComparisonCategoryType Kind) { |
| 10616 | return CheckComparisonCategoryType(Kind, Loc); |
| 10617 | }; |
| 10618 | |
| 10619 | // C++2a [expr.spaceship]p7: If the composite pointer type is a function |
| 10620 | // pointer type, a pointer-to-member type, or std::nullptr_t, the |
| 10621 | // result is of type std::strong_equality |
| 10622 | if (CompositeTy->isFunctionPointerType() || |
| 10623 | CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) |
| 10624 | // FIXME: consider making the function pointer case produce |
| 10625 | // strong_ordering not strong_equality, per P0946R0-Jax18 discussion |
| 10626 | // and direction polls |
| 10627 | return buildResultTy(ComparisonCategoryType::StrongEquality); |
| 10628 | |
| 10629 | // C++2a [expr.spaceship]p8: If the composite pointer type is an object |
| 10630 | // pointer type, p <=> q is of type std::strong_ordering. |
| 10631 | if (CompositeTy->isPointerType()) { |
| 10632 | // P0946R0: Comparisons between a null pointer constant and an object |
| 10633 | // pointer result in std::strong_equality |
| 10634 | if (LHSIsNull != RHSIsNull) |
| 10635 | return buildResultTy(ComparisonCategoryType::StrongEquality); |
| 10636 | return buildResultTy(ComparisonCategoryType::StrongOrdering); |
| 10637 | } |
| 10638 | // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. |
| 10639 | // TODO: Extend support for operator<=> to ObjC types. |
| 10640 | return InvalidOperands(Loc, LHS, RHS); |
| 10641 | }; |
| 10642 | |
| 10643 | |
| 10644 | if (!IsRelational && LHSIsNull != RHSIsNull) { |
| 10645 | bool IsEquality = Opc == BO_EQ; |
| 10646 | if (RHSIsNull) |
| 10647 | DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, |
| 10648 | RHS.get()->getSourceRange()); |
| 10649 | else |
| 10650 | DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, |
| 10651 | LHS.get()->getSourceRange()); |
| 10652 | } |
| 10653 | |
| 10654 | if ((LHSType->isIntegerType() && !LHSIsNull) || |
| 10655 | (RHSType->isIntegerType() && !RHSIsNull)) { |
| 10656 | // Skip normal pointer conversion checks in this case; we have better |
| 10657 | // diagnostics for this below. |
| 10658 | } else if (getLangOpts().CPlusPlus) { |
| 10659 | // Equality comparison of a function pointer to a void pointer is invalid, |
| 10660 | // but we allow it as an extension. |
| 10661 | // FIXME: If we really want to allow this, should it be part of composite |
| 10662 | // pointer type computation so it works in conditionals too? |
| 10663 | if (!IsRelational && |
| 10664 | ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || |
| 10665 | (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { |
| 10666 | // This is a gcc extension compatibility comparison. |
| 10667 | // In a SFINAE context, we treat this as a hard error to maintain |
| 10668 | // conformance with the C++ standard. |
| 10669 | diagnoseFunctionPointerToVoidComparison( |
| 10670 | *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); |
| 10671 | |
| 10672 | if (isSFINAEContext()) |
| 10673 | return QualType(); |
| 10674 | |
| 10675 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); |
| 10676 | return computeResultTy(); |
| 10677 | } |
| 10678 | |
| 10679 | // C++ [expr.eq]p2: |
| 10680 | // If at least one operand is a pointer [...] bring them to their |
| 10681 | // composite pointer type. |
| 10682 | // C++ [expr.spaceship]p6 |
| 10683 | // If at least one of the operands is of pointer type, [...] bring them |
| 10684 | // to their composite pointer type. |
| 10685 | // C++ [expr.rel]p2: |
| 10686 | // If both operands are pointers, [...] bring them to their composite |
| 10687 | // pointer type. |
| 10688 | if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= |
| 10689 | (IsRelational ? 2 : 1) && |
| 10690 | (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || |
| 10691 | RHSType->isObjCObjectPointerType()))) { |
| 10692 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) |
| 10693 | return QualType(); |
| 10694 | return computeResultTy(); |
| 10695 | } |
| 10696 | } else if (LHSType->isPointerType() && |
| 10697 | RHSType->isPointerType()) { // C99 6.5.8p2 |
| 10698 | bool LHSIsCap = LHSType->isCHERICapabilityType(Context); |
| 10699 | bool RHSIsCap = RHSType->isCHERICapabilityType(Context); |
| 10700 | |
| 10701 | // Binary operations between pointers and capabilities are errors |
| 10702 | if (LHSIsCap != RHSIsCap && !(LHSIsNull || RHSIsNull)) |
| 10703 | Diag(Loc, diag::err_typecheck_comparison_of_pointer_capability) |
| 10704 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10705 | << RHS.get()->getSourceRange(); |
| 10706 | |
| 10707 | // We only implicitly cast the NULL constant to a memory capability |
| 10708 | if (LHSIsNull && !LHSIsCap && RHSIsCap) |
| 10709 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_PointerToCHERICapability); |
| 10710 | else if (RHSIsNull && !RHSIsCap && LHSIsCap) |
| 10711 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_PointerToCHERICapability); |
| 10712 | |
| 10713 | // All of the following pointer-related warnings are GCC extensions, except |
| 10714 | // when handling null pointer constants. |
| 10715 | QualType LCanPointeeTy = |
| 10716 | LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
| 10717 | QualType RCanPointeeTy = |
| 10718 | RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); |
| 10719 | |
| 10720 | // C99 6.5.9p2 and C99 6.5.8p2 |
| 10721 | if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), |
| 10722 | RCanPointeeTy.getUnqualifiedType())) { |
| 10723 | // Valid unless a relational comparison of function pointers |
| 10724 | if (IsRelational && LCanPointeeTy->isFunctionType()) { |
| 10725 | Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) |
| 10726 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10727 | << RHS.get()->getSourceRange(); |
| 10728 | } |
| 10729 | } else if (!IsRelational && |
| 10730 | (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { |
| 10731 | // Valid unless comparison between non-null pointer and function pointer |
| 10732 | if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) |
| 10733 | && !LHSIsNull && !RHSIsNull) |
| 10734 | diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, |
| 10735 | /*isError*/false); |
| 10736 | } else { |
| 10737 | // Invalid |
| 10738 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); |
| 10739 | } |
| 10740 | if (LCanPointeeTy != RCanPointeeTy) { |
| 10741 | // Treat NULL constant as a special case in OpenCL. |
| 10742 | if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { |
| 10743 | const PointerType *LHSPtr = LHSType->getAs<PointerType>(); |
| 10744 | if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { |
| 10745 | Diag(Loc, |
| 10746 | diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) |
| 10747 | << LHSType << RHSType << 0 /* comparison */ |
| 10748 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 10749 | } |
| 10750 | } |
| 10751 | LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); |
| 10752 | LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); |
| 10753 | CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion |
| 10754 | : CK_BitCast; |
| 10755 | if (LHSIsNull && !RHSIsNull) |
| 10756 | LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); |
| 10757 | else |
| 10758 | RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); |
| 10759 | } |
| 10760 | return computeResultTy(); |
| 10761 | } |
| 10762 | |
| 10763 | if (getLangOpts().CPlusPlus) { |
| 10764 | // C++ [expr.eq]p4: |
| 10765 | // Two operands of type std::nullptr_t or one operand of type |
| 10766 | // std::nullptr_t and the other a null pointer constant compare equal. |
| 10767 | if (!IsRelational && LHSIsNull && RHSIsNull) { |
| 10768 | if (LHSType->isNullPtrType()) { |
| 10769 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); |
| 10770 | return computeResultTy(); |
| 10771 | } |
| 10772 | if (RHSType->isNullPtrType()) { |
| 10773 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); |
| 10774 | return computeResultTy(); |
| 10775 | } |
| 10776 | } |
| 10777 | |
| 10778 | // Comparison of Objective-C pointers and block pointers against nullptr_t. |
| 10779 | // These aren't covered by the composite pointer type rules. |
| 10780 | if (!IsRelational && RHSType->isNullPtrType() && |
| 10781 | (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { |
| 10782 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); |
| 10783 | return computeResultTy(); |
| 10784 | } |
| 10785 | if (!IsRelational && LHSType->isNullPtrType() && |
| 10786 | (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { |
| 10787 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); |
| 10788 | return computeResultTy(); |
| 10789 | } |
| 10790 | |
| 10791 | if (IsRelational && |
| 10792 | ((LHSType->isNullPtrType() && RHSType->isPointerType()) || |
| 10793 | (RHSType->isNullPtrType() && LHSType->isPointerType()))) { |
| 10794 | // HACK: Relational comparison of nullptr_t against a pointer type is |
| 10795 | // invalid per DR583, but we allow it within std::less<> and friends, |
| 10796 | // since otherwise common uses of it break. |
| 10797 | // FIXME: Consider removing this hack once LWG fixes std::less<> and |
| 10798 | // friends to have std::nullptr_t overload candidates. |
| 10799 | DeclContext *DC = CurContext; |
| 10800 | if (isa<FunctionDecl>(DC)) |
| 10801 | DC = DC->getParent(); |
| 10802 | if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { |
| 10803 | if (CTSD->isInStdNamespace() && |
| 10804 | llvm::StringSwitch<bool>(CTSD->getName()) |
| 10805 | .Cases("less" , "less_equal" , "greater" , "greater_equal" , true) |
| 10806 | .Default(false)) { |
| 10807 | if (RHSType->isNullPtrType()) |
| 10808 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); |
| 10809 | else |
| 10810 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); |
| 10811 | return computeResultTy(); |
| 10812 | } |
| 10813 | } |
| 10814 | } |
| 10815 | |
| 10816 | // C++ [expr.eq]p2: |
| 10817 | // If at least one operand is a pointer to member, [...] bring them to |
| 10818 | // their composite pointer type. |
| 10819 | if (!IsRelational && |
| 10820 | (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { |
| 10821 | if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) |
| 10822 | return QualType(); |
| 10823 | else |
| 10824 | return computeResultTy(); |
| 10825 | } |
| 10826 | } |
| 10827 | |
| 10828 | // Handle block pointer types. |
| 10829 | if (!IsRelational && LHSType->isBlockPointerType() && |
| 10830 | RHSType->isBlockPointerType()) { |
| 10831 | QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); |
| 10832 | QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); |
| 10833 | |
| 10834 | if (!LHSIsNull && !RHSIsNull && |
| 10835 | !Context.typesAreCompatible(lpointee, rpointee)) { |
| 10836 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) |
| 10837 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10838 | << RHS.get()->getSourceRange(); |
| 10839 | } |
| 10840 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); |
| 10841 | return computeResultTy(); |
| 10842 | } |
| 10843 | |
| 10844 | // Allow block pointers to be compared with null pointer constants. |
| 10845 | if (!IsRelational |
| 10846 | && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) |
| 10847 | || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { |
| 10848 | if (!LHSIsNull && !RHSIsNull) { |
| 10849 | if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() |
| 10850 | ->getPointeeType()->isVoidType()) |
| 10851 | || (LHSType->isPointerType() && LHSType->castAs<PointerType>() |
| 10852 | ->getPointeeType()->isVoidType()))) |
| 10853 | Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) |
| 10854 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10855 | << RHS.get()->getSourceRange(); |
| 10856 | } |
| 10857 | if (LHSIsNull && !RHSIsNull) |
| 10858 | LHS = ImpCastExprToType(LHS.get(), RHSType, |
| 10859 | RHSType->isPointerType() ? CK_BitCast |
| 10860 | : CK_AnyPointerToBlockPointerCast); |
| 10861 | else |
| 10862 | RHS = ImpCastExprToType(RHS.get(), LHSType, |
| 10863 | LHSType->isPointerType() ? CK_BitCast |
| 10864 | : CK_AnyPointerToBlockPointerCast); |
| 10865 | return computeResultTy(); |
| 10866 | } |
| 10867 | |
| 10868 | if (LHSType->isObjCObjectPointerType() || |
| 10869 | RHSType->isObjCObjectPointerType()) { |
| 10870 | const PointerType *LPT = LHSType->getAs<PointerType>(); |
| 10871 | const PointerType *RPT = RHSType->getAs<PointerType>(); |
| 10872 | if (LPT || RPT) { |
| 10873 | bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; |
| 10874 | bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; |
| 10875 | |
| 10876 | if (!LPtrToVoid && !RPtrToVoid && |
| 10877 | !Context.typesAreCompatible(LHSType, RHSType)) { |
| 10878 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, |
| 10879 | /*isError*/false); |
| 10880 | } |
| 10881 | if (LHSIsNull && !RHSIsNull) { |
| 10882 | Expr *E = LHS.get(); |
| 10883 | if (getLangOpts().ObjCAutoRefCount) |
| 10884 | CheckObjCConversion(SourceRange(), RHSType, E, |
| 10885 | CCK_ImplicitConversion); |
| 10886 | LHS = ImpCastExprToType(E, RHSType, |
| 10887 | RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
| 10888 | } |
| 10889 | else { |
| 10890 | Expr *E = RHS.get(); |
| 10891 | if (getLangOpts().ObjCAutoRefCount) |
| 10892 | CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, |
| 10893 | /*Diagnose=*/true, |
| 10894 | /*DiagnoseCFAudited=*/false, Opc); |
| 10895 | RHS = ImpCastExprToType(E, LHSType, |
| 10896 | LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); |
| 10897 | } |
| 10898 | return computeResultTy(); |
| 10899 | } |
| 10900 | if (LHSType->isObjCObjectPointerType() && |
| 10901 | RHSType->isObjCObjectPointerType()) { |
| 10902 | if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) |
| 10903 | diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, |
| 10904 | /*isError*/false); |
| 10905 | if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) |
| 10906 | diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); |
| 10907 | |
| 10908 | if (LHSIsNull && !RHSIsNull) |
| 10909 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); |
| 10910 | else |
| 10911 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); |
| 10912 | return computeResultTy(); |
| 10913 | } |
| 10914 | |
| 10915 | if (!IsRelational && LHSType->isBlockPointerType() && |
| 10916 | RHSType->isBlockCompatibleObjCPointerType(Context)) { |
| 10917 | LHS = ImpCastExprToType(LHS.get(), RHSType, |
| 10918 | CK_BlockPointerToObjCPointerCast); |
| 10919 | return computeResultTy(); |
| 10920 | } else if (!IsRelational && |
| 10921 | LHSType->isBlockCompatibleObjCPointerType(Context) && |
| 10922 | RHSType->isBlockPointerType()) { |
| 10923 | RHS = ImpCastExprToType(RHS.get(), LHSType, |
| 10924 | CK_BlockPointerToObjCPointerCast); |
| 10925 | return computeResultTy(); |
| 10926 | } |
| 10927 | } |
| 10928 | if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || |
| 10929 | (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { |
| 10930 | unsigned DiagID = 0; |
| 10931 | bool isError = false; |
| 10932 | if (LangOpts.DebuggerSupport) { |
| 10933 | // Under a debugger, allow the comparison of pointers to integers, |
| 10934 | // since users tend to want to compare addresses. |
| 10935 | } else if ((LHSIsNull && LHSType->isIntegerType()) || |
| 10936 | (RHSIsNull && RHSType->isIntegerType())) { |
| 10937 | if (IsRelational) { |
| 10938 | isError = getLangOpts().CPlusPlus; |
| 10939 | DiagID = |
| 10940 | isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero |
| 10941 | : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; |
| 10942 | } |
| 10943 | } else if (getLangOpts().CPlusPlus) { |
| 10944 | DiagID = diag::err_typecheck_comparison_of_pointer_integer; |
| 10945 | isError = true; |
| 10946 | } else if (IsRelational) |
| 10947 | DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; |
| 10948 | else |
| 10949 | DiagID = diag::ext_typecheck_comparison_of_pointer_integer; |
| 10950 | |
| 10951 | if (DiagID) { |
| 10952 | Diag(Loc, DiagID) |
| 10953 | << LHSType << RHSType << LHS.get()->getSourceRange() |
| 10954 | << RHS.get()->getSourceRange(); |
| 10955 | if (isError) |
| 10956 | return QualType(); |
| 10957 | } |
| 10958 | |
| 10959 | if (LHSType->isIntegerType()) |
| 10960 | LHS = ImpCastExprToType(LHS.get(), RHSType, |
| 10961 | LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
| 10962 | else |
| 10963 | RHS = ImpCastExprToType(RHS.get(), LHSType, |
| 10964 | RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); |
| 10965 | return computeResultTy(); |
| 10966 | } |
| 10967 | |
| 10968 | // Handle block pointers. |
| 10969 | if (!IsRelational && RHSIsNull |
| 10970 | && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { |
| 10971 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); |
| 10972 | return computeResultTy(); |
| 10973 | } |
| 10974 | if (!IsRelational && LHSIsNull |
| 10975 | && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { |
| 10976 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); |
| 10977 | return computeResultTy(); |
| 10978 | } |
| 10979 | |
| 10980 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { |
| 10981 | if (LHSType->isClkEventT() && RHSType->isClkEventT()) { |
| 10982 | return computeResultTy(); |
| 10983 | } |
| 10984 | |
| 10985 | if (LHSType->isQueueT() && RHSType->isQueueT()) { |
| 10986 | return computeResultTy(); |
| 10987 | } |
| 10988 | |
| 10989 | if (LHSIsNull && RHSType->isQueueT()) { |
| 10990 | LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); |
| 10991 | return computeResultTy(); |
| 10992 | } |
| 10993 | |
| 10994 | if (LHSType->isQueueT() && RHSIsNull) { |
| 10995 | RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); |
| 10996 | return computeResultTy(); |
| 10997 | } |
| 10998 | } |
| 10999 | |
| 11000 | return InvalidOperands(Loc, LHS, RHS); |
| 11001 | } |
| 11002 | |
| 11003 | // Return a signed ext_vector_type that is of identical size and number of |
| 11004 | // elements. For floating point vectors, return an integer type of identical |
| 11005 | // size and number of elements. In the non ext_vector_type case, search from |
| 11006 | // the largest type to the smallest type to avoid cases where long long == long, |
| 11007 | // where long gets picked over long long. |
| 11008 | QualType Sema::GetSignedVectorType(QualType V) { |
| 11009 | const VectorType *VTy = V->getAs<VectorType>(); |
| 11010 | unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); |
| 11011 | |
| 11012 | if (isa<ExtVectorType>(VTy)) { |
| 11013 | if (TypeSize == Context.getTypeSize(Context.CharTy)) |
| 11014 | return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); |
| 11015 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) |
| 11016 | return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); |
| 11017 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) |
| 11018 | return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); |
| 11019 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) |
| 11020 | return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); |
| 11021 | assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && |
| 11022 | "Unhandled vector element size in vector compare" ); |
| 11023 | return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); |
| 11024 | } |
| 11025 | |
| 11026 | if (TypeSize == Context.getTypeSize(Context.LongLongTy)) |
| 11027 | return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), |
| 11028 | VectorType::GenericVector); |
| 11029 | else if (TypeSize == Context.getTypeSize(Context.LongTy)) |
| 11030 | return Context.getVectorType(Context.LongTy, VTy->getNumElements(), |
| 11031 | VectorType::GenericVector); |
| 11032 | else if (TypeSize == Context.getTypeSize(Context.IntTy)) |
| 11033 | return Context.getVectorType(Context.IntTy, VTy->getNumElements(), |
| 11034 | VectorType::GenericVector); |
| 11035 | else if (TypeSize == Context.getTypeSize(Context.ShortTy)) |
| 11036 | return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), |
| 11037 | VectorType::GenericVector); |
| 11038 | assert(TypeSize == Context.getTypeSize(Context.CharTy) && |
| 11039 | "Unhandled vector element size in vector compare" ); |
| 11040 | return Context.getVectorType(Context.CharTy, VTy->getNumElements(), |
| 11041 | VectorType::GenericVector); |
| 11042 | } |
| 11043 | |
| 11044 | /// CheckVectorCompareOperands - vector comparisons are a clang extension that |
| 11045 | /// operates on extended vector types. Instead of producing an IntTy result, |
| 11046 | /// like a scalar comparison, a vector comparison produces a vector of integer |
| 11047 | /// types. |
| 11048 | QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, |
| 11049 | SourceLocation Loc, |
| 11050 | BinaryOperatorKind Opc) { |
| 11051 | // Check to make sure we're operating on vectors of the same type and width, |
| 11052 | // Allowing one side to be a scalar of element type. |
| 11053 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, |
| 11054 | /*AllowBothBool*/true, |
| 11055 | /*AllowBoolConversions*/getLangOpts().ZVector); |
| 11056 | if (vType.isNull()) |
| 11057 | return vType; |
| 11058 | |
| 11059 | QualType LHSType = LHS.get()->getType(); |
| 11060 | |
| 11061 | // If AltiVec, the comparison results in a numeric type, i.e. |
| 11062 | // bool for C++, int for C |
| 11063 | if (getLangOpts().AltiVec && |
| 11064 | vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) |
| 11065 | return Context.getLogicalOperationType(); |
| 11066 | |
| 11067 | // For non-floating point types, check for self-comparisons of the form |
| 11068 | // x == x, x != x, x < x, etc. These always evaluate to a constant, and |
| 11069 | // often indicate logic errors in the program. |
| 11070 | diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); |
| 11071 | |
| 11072 | // Check for comparisons of floating point operands using != and ==. |
| 11073 | if (BinaryOperator::isEqualityOp(Opc) && |
| 11074 | LHSType->hasFloatingRepresentation()) { |
| 11075 | assert(RHS.get()->getType()->hasFloatingRepresentation()); |
| 11076 | CheckFloatComparison(Loc, LHS.get(), RHS.get()); |
| 11077 | } |
| 11078 | |
| 11079 | // Return a signed type for the vector. |
| 11080 | return GetSignedVectorType(vType); |
| 11081 | } |
| 11082 | |
| 11083 | QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
| 11084 | SourceLocation Loc) { |
| 11085 | // Ensure that either both operands are of the same vector type, or |
| 11086 | // one operand is of a vector type and the other is of its element type. |
| 11087 | QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, |
| 11088 | /*AllowBothBool*/true, |
| 11089 | /*AllowBoolConversions*/false); |
| 11090 | if (vType.isNull()) |
| 11091 | return InvalidOperands(Loc, LHS, RHS); |
| 11092 | if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && |
| 11093 | !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) |
| 11094 | return InvalidOperands(Loc, LHS, RHS); |
| 11095 | // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the |
| 11096 | // usage of the logical operators && and || with vectors in C. This |
| 11097 | // check could be notionally dropped. |
| 11098 | if (!getLangOpts().CPlusPlus && |
| 11099 | !(isa<ExtVectorType>(vType->getAs<VectorType>()))) |
| 11100 | return InvalidLogicalVectorOperands(Loc, LHS, RHS); |
| 11101 | |
| 11102 | return GetSignedVectorType(LHS.get()->getType()); |
| 11103 | } |
| 11104 | |
| 11105 | inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, |
| 11106 | SourceLocation Loc, |
| 11107 | BinaryOperatorKind Opc) { |
| 11108 | checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); |
| 11109 | |
| 11110 | // For the CHERI checks below we want to look at the unpromoted type |
| 11111 | QualType OriginalLHSType = LHS.get()->getType(); |
| 11112 | |
| 11113 | bool IsCompAssign = |
| 11114 | Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; |
| 11115 | |
| 11116 | if (LHS.get()->getType()->isVectorType() || |
| 11117 | RHS.get()->getType()->isVectorType()) { |
| 11118 | if (LHS.get()->getType()->hasIntegerRepresentation() && |
| 11119 | RHS.get()->getType()->hasIntegerRepresentation()) |
| 11120 | return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, |
| 11121 | /*AllowBothBool*/true, |
| 11122 | /*AllowBoolConversions*/getLangOpts().ZVector); |
| 11123 | return InvalidOperands(Loc, LHS, RHS); |
| 11124 | } |
| 11125 | |
| 11126 | if (Opc == BO_And) |
| 11127 | diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); |
| 11128 | |
| 11129 | ExprResult LHSResult = LHS, RHSResult = RHS; |
| 11130 | QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, |
| 11131 | IsCompAssign); |
| 11132 | if (LHSResult.isInvalid() || RHSResult.isInvalid()) |
| 11133 | return QualType(); |
| 11134 | LHS = LHSResult.get(); |
| 11135 | RHS = RHSResult.get(); |
| 11136 | |
| 11137 | if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) { |
| 11138 | bool isLHSCap = OriginalLHSType->isCHERICapabilityType(Context); |
| 11139 | bool isRHSCap = RHS.get()->getType()->isCHERICapabilityType(Context); |
| 11140 | bool UsingUIntCapOffset = getLangOpts().cheriUIntCapUsesOffset(); |
| 11141 | if (isLHSCap && (Opc == BO_And || Opc == BO_AndAssign)) { |
| 11142 | // Bitwise and can cause checking low pointer bits to be compiled to |
| 11143 | // and always false condition (see CTSRD-CHERI/clang#189) unless we |
| 11144 | // have CheriDataDependentProvenance enabled. It also gives surprising |
| 11145 | // behaviour if we are compiling in uintcap=offset mode so warn if either |
| 11146 | // of these conditions are met: |
| 11147 | if (UsingUIntCapOffset || !getLangOpts().CheriDataDependentProvenance) |
| 11148 | DiagRuntimeBehavior(Loc, RHS.get(), |
| 11149 | PDiag(diag::warn_uintcap_bitwise_and) |
| 11150 | << LHS.get()->getSourceRange() |
| 11151 | << RHS.get()->getSourceRange()); |
| 11152 | } else if (UsingUIntCapOffset && isLHSCap && |
| 11153 | (Opc == BO_Xor || Opc == BO_XorAssign)) { |
| 11154 | // XOR is highly dubious when in offset mode (except when using on plain |
| 11155 | // integer values, but then the user should be using size_t/vaddr_t and |
| 11156 | // not uintcap_t. Don't warn in address mode since that works just fine |
| 11157 | // (only slightly less efficiently) |
| 11158 | DiagRuntimeBehavior(Loc, RHS.get(), |
| 11159 | PDiag(diag::warn_uintcap_bad_bitwise_op) |
| 11160 | << 0 /*=xor*/ << 0 /* usecase is hashing */ |
| 11161 | << LHS.get()->getSourceRange() |
| 11162 | << RHS.get()->getSourceRange()); |
| 11163 | } else if ((isLHSCap && !isRHSCap) || (!isLHSCap && isRHSCap)) { |
| 11164 | // FIXME: this warning is not always useful |
| 11165 | DiagRuntimeBehavior(Loc, RHS.get(), |
| 11166 | PDiag(diag::warn_mixed_capability_binop) |
| 11167 | << OriginalLHSType << RHS.get()->getType() |
| 11168 | << LHS.get()->getSourceRange() |
| 11169 | << RHS.get()->getSourceRange()); |
| 11170 | } |
| 11171 | return compType; |
| 11172 | } |
| 11173 | return InvalidOperands(Loc, LHS, RHS); |
| 11174 | } |
| 11175 | |
| 11176 | // C99 6.5.[13,14] |
| 11177 | inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, |
| 11178 | SourceLocation Loc, |
| 11179 | BinaryOperatorKind Opc) { |
| 11180 | // Check vector operands differently. |
| 11181 | if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) |
| 11182 | return CheckVectorLogicalOperands(LHS, RHS, Loc); |
| 11183 | |
| 11184 | // Diagnose cases where the user write a logical and/or but probably meant a |
| 11185 | // bitwise one. We do this when the LHS is a non-bool integer and the RHS |
| 11186 | // is a constant. |
| 11187 | if (LHS.get()->getType()->isIntegerType() && |
| 11188 | !LHS.get()->getType()->isBooleanType() && |
| 11189 | RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && |
| 11190 | // Don't warn in macros or template instantiations. |
| 11191 | !Loc.isMacroID() && !inTemplateInstantiation()) { |
| 11192 | // If the RHS can be constant folded, and if it constant folds to something |
| 11193 | // that isn't 0 or 1 (which indicate a potential logical operation that |
| 11194 | // happened to fold to true/false) then warn. |
| 11195 | // Parens on the RHS are ignored. |
| 11196 | Expr::EvalResult EVResult; |
| 11197 | if (RHS.get()->EvaluateAsInt(EVResult, Context)) { |
| 11198 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 11199 | if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && |
| 11200 | !RHS.get()->getExprLoc().isMacroID()) || |
| 11201 | (Result != 0 && Result != 1)) { |
| 11202 | Diag(Loc, diag::warn_logical_instead_of_bitwise) |
| 11203 | << RHS.get()->getSourceRange() |
| 11204 | << (Opc == BO_LAnd ? "&&" : "||" ); |
| 11205 | // Suggest replacing the logical operator with the bitwise version |
| 11206 | Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) |
| 11207 | << (Opc == BO_LAnd ? "&" : "|" ) |
| 11208 | << FixItHint::CreateReplacement(SourceRange( |
| 11209 | Loc, getLocForEndOfToken(Loc)), |
| 11210 | Opc == BO_LAnd ? "&" : "|" ); |
| 11211 | if (Opc == BO_LAnd) |
| 11212 | // Suggest replacing "Foo() && kNonZero" with "Foo()" |
| 11213 | Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) |
| 11214 | << FixItHint::CreateRemoval( |
| 11215 | SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), |
| 11216 | RHS.get()->getEndLoc())); |
| 11217 | } |
| 11218 | } |
| 11219 | } |
| 11220 | |
| 11221 | if (!Context.getLangOpts().CPlusPlus) { |
| 11222 | // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do |
| 11223 | // not operate on the built-in scalar and vector float types. |
| 11224 | if (Context.getLangOpts().OpenCL && |
| 11225 | Context.getLangOpts().OpenCLVersion < 120) { |
| 11226 | if (LHS.get()->getType()->isFloatingType() || |
| 11227 | RHS.get()->getType()->isFloatingType()) |
| 11228 | return InvalidOperands(Loc, LHS, RHS); |
| 11229 | } |
| 11230 | |
| 11231 | LHS = UsualUnaryConversions(LHS.get()); |
| 11232 | if (LHS.isInvalid()) |
| 11233 | return QualType(); |
| 11234 | |
| 11235 | RHS = UsualUnaryConversions(RHS.get()); |
| 11236 | if (RHS.isInvalid()) |
| 11237 | return QualType(); |
| 11238 | |
| 11239 | if (!LHS.get()->getType()->isScalarType() || |
| 11240 | !RHS.get()->getType()->isScalarType()) |
| 11241 | return InvalidOperands(Loc, LHS, RHS); |
| 11242 | |
| 11243 | return Context.IntTy; |
| 11244 | } |
| 11245 | |
| 11246 | // The following is safe because we only use this method for |
| 11247 | // non-overloadable operands. |
| 11248 | |
| 11249 | // C++ [expr.log.and]p1 |
| 11250 | // C++ [expr.log.or]p1 |
| 11251 | // The operands are both contextually converted to type bool. |
| 11252 | ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); |
| 11253 | if (LHSRes.isInvalid()) |
| 11254 | return InvalidOperands(Loc, LHS, RHS); |
| 11255 | LHS = LHSRes; |
| 11256 | |
| 11257 | ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); |
| 11258 | if (RHSRes.isInvalid()) |
| 11259 | return InvalidOperands(Loc, LHS, RHS); |
| 11260 | RHS = RHSRes; |
| 11261 | |
| 11262 | // C++ [expr.log.and]p2 |
| 11263 | // C++ [expr.log.or]p2 |
| 11264 | // The result is a bool. |
| 11265 | return Context.BoolTy; |
| 11266 | } |
| 11267 | |
| 11268 | static bool IsReadonlyMessage(Expr *E, Sema &S) { |
| 11269 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); |
| 11270 | if (!ME) return false; |
| 11271 | if (!isa<FieldDecl>(ME->getMemberDecl())) return false; |
| 11272 | ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( |
| 11273 | ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); |
| 11274 | if (!Base) return false; |
| 11275 | return Base->getMethodDecl() != nullptr; |
| 11276 | } |
| 11277 | |
| 11278 | /// Is the given expression (which must be 'const') a reference to a |
| 11279 | /// variable which was originally non-const, but which has become |
| 11280 | /// 'const' due to being captured within a block? |
| 11281 | enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; |
| 11282 | static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { |
| 11283 | assert(E->isLValue() && E->getType().isConstQualified()); |
| 11284 | E = E->IgnoreParens(); |
| 11285 | |
| 11286 | // Must be a reference to a declaration from an enclosing scope. |
| 11287 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); |
| 11288 | if (!DRE) return NCCK_None; |
| 11289 | if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; |
| 11290 | |
| 11291 | // The declaration must be a variable which is not declared 'const'. |
| 11292 | VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); |
| 11293 | if (!var) return NCCK_None; |
| 11294 | if (var->getType().isConstQualified()) return NCCK_None; |
| 11295 | assert(var->hasLocalStorage() && "capture added 'const' to non-local?" ); |
| 11296 | |
| 11297 | // Decide whether the first capture was for a block or a lambda. |
| 11298 | DeclContext *DC = S.CurContext, *Prev = nullptr; |
| 11299 | // Decide whether the first capture was for a block or a lambda. |
| 11300 | while (DC) { |
| 11301 | // For init-capture, it is possible that the variable belongs to the |
| 11302 | // template pattern of the current context. |
| 11303 | if (auto *FD = dyn_cast<FunctionDecl>(DC)) |
| 11304 | if (var->isInitCapture() && |
| 11305 | FD->getTemplateInstantiationPattern() == var->getDeclContext()) |
| 11306 | break; |
| 11307 | if (DC == var->getDeclContext()) |
| 11308 | break; |
| 11309 | Prev = DC; |
| 11310 | DC = DC->getParent(); |
| 11311 | } |
| 11312 | // Unless we have an init-capture, we've gone one step too far. |
| 11313 | if (!var->isInitCapture()) |
| 11314 | DC = Prev; |
| 11315 | return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); |
| 11316 | } |
| 11317 | |
| 11318 | static bool IsTypeModifiable(QualType Ty, bool IsDereference) { |
| 11319 | Ty = Ty.getNonReferenceType(); |
| 11320 | if (IsDereference && Ty->isPointerType()) |
| 11321 | Ty = Ty->getPointeeType(); |
| 11322 | return !Ty.isConstQualified(); |
| 11323 | } |
| 11324 | |
| 11325 | // Update err_typecheck_assign_const and note_typecheck_assign_const |
| 11326 | // when this enum is changed. |
| 11327 | enum { |
| 11328 | ConstFunction, |
| 11329 | ConstVariable, |
| 11330 | ConstMember, |
| 11331 | ConstMethod, |
| 11332 | NestedConstMember, |
| 11333 | ConstUnknown, // Keep as last element |
| 11334 | }; |
| 11335 | |
| 11336 | /// Emit the "read-only variable not assignable" error and print notes to give |
| 11337 | /// more information about why the variable is not assignable, such as pointing |
| 11338 | /// to the declaration of a const variable, showing that a method is const, or |
| 11339 | /// that the function is returning a const reference. |
| 11340 | static void DiagnoseConstAssignment(Sema &S, const Expr *E, |
| 11341 | SourceLocation Loc) { |
| 11342 | SourceRange ExprRange = E->getSourceRange(); |
| 11343 | |
| 11344 | // Only emit one error on the first const found. All other consts will emit |
| 11345 | // a note to the error. |
| 11346 | bool DiagnosticEmitted = false; |
| 11347 | |
| 11348 | // Track if the current expression is the result of a dereference, and if the |
| 11349 | // next checked expression is the result of a dereference. |
| 11350 | bool IsDereference = false; |
| 11351 | bool NextIsDereference = false; |
| 11352 | |
| 11353 | // Loop to process MemberExpr chains. |
| 11354 | while (true) { |
| 11355 | IsDereference = NextIsDereference; |
| 11356 | |
| 11357 | E = E->IgnoreImplicit()->IgnoreParenImpCasts(); |
| 11358 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { |
| 11359 | NextIsDereference = ME->isArrow(); |
| 11360 | const ValueDecl *VD = ME->getMemberDecl(); |
| 11361 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { |
| 11362 | // Mutable fields can be modified even if the class is const. |
| 11363 | if (Field->isMutable()) { |
| 11364 | assert(DiagnosticEmitted && "Expected diagnostic not emitted." ); |
| 11365 | break; |
| 11366 | } |
| 11367 | |
| 11368 | if (!IsTypeModifiable(Field->getType(), IsDereference)) { |
| 11369 | if (!DiagnosticEmitted) { |
| 11370 | S.Diag(Loc, diag::err_typecheck_assign_const) |
| 11371 | << ExprRange << ConstMember << false /*static*/ << Field |
| 11372 | << Field->getType(); |
| 11373 | DiagnosticEmitted = true; |
| 11374 | } |
| 11375 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) |
| 11376 | << ConstMember << false /*static*/ << Field << Field->getType() |
| 11377 | << Field->getSourceRange(); |
| 11378 | } |
| 11379 | E = ME->getBase(); |
| 11380 | continue; |
| 11381 | } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { |
| 11382 | if (VDecl->getType().isConstQualified()) { |
| 11383 | if (!DiagnosticEmitted) { |
| 11384 | S.Diag(Loc, diag::err_typecheck_assign_const) |
| 11385 | << ExprRange << ConstMember << true /*static*/ << VDecl |
| 11386 | << VDecl->getType(); |
| 11387 | DiagnosticEmitted = true; |
| 11388 | } |
| 11389 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) |
| 11390 | << ConstMember << true /*static*/ << VDecl << VDecl->getType() |
| 11391 | << VDecl->getSourceRange(); |
| 11392 | } |
| 11393 | // Static fields do not inherit constness from parents. |
| 11394 | break; |
| 11395 | } |
| 11396 | break; // End MemberExpr |
| 11397 | } else if (const ArraySubscriptExpr *ASE = |
| 11398 | dyn_cast<ArraySubscriptExpr>(E)) { |
| 11399 | E = ASE->getBase()->IgnoreParenImpCasts(); |
| 11400 | continue; |
| 11401 | } else if (const ExtVectorElementExpr *EVE = |
| 11402 | dyn_cast<ExtVectorElementExpr>(E)) { |
| 11403 | E = EVE->getBase()->IgnoreParenImpCasts(); |
| 11404 | continue; |
| 11405 | } |
| 11406 | break; |
| 11407 | } |
| 11408 | |
| 11409 | if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { |
| 11410 | // Function calls |
| 11411 | const FunctionDecl *FD = CE->getDirectCallee(); |
| 11412 | if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { |
| 11413 | if (!DiagnosticEmitted) { |
| 11414 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange |
| 11415 | << ConstFunction << FD; |
| 11416 | DiagnosticEmitted = true; |
| 11417 | } |
| 11418 | S.Diag(FD->getReturnTypeSourceRange().getBegin(), |
| 11419 | diag::note_typecheck_assign_const) |
| 11420 | << ConstFunction << FD << FD->getReturnType() |
| 11421 | << FD->getReturnTypeSourceRange(); |
| 11422 | } |
| 11423 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { |
| 11424 | // Point to variable declaration. |
| 11425 | if (const ValueDecl *VD = DRE->getDecl()) { |
| 11426 | if (!IsTypeModifiable(VD->getType(), IsDereference)) { |
| 11427 | if (!DiagnosticEmitted) { |
| 11428 | S.Diag(Loc, diag::err_typecheck_assign_const) |
| 11429 | << ExprRange << ConstVariable << VD << VD->getType(); |
| 11430 | DiagnosticEmitted = true; |
| 11431 | } |
| 11432 | S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) |
| 11433 | << ConstVariable << VD << VD->getType() << VD->getSourceRange(); |
| 11434 | } |
| 11435 | } |
| 11436 | } else if (isa<CXXThisExpr>(E)) { |
| 11437 | if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { |
| 11438 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { |
| 11439 | if (MD->isConst()) { |
| 11440 | if (!DiagnosticEmitted) { |
| 11441 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange |
| 11442 | << ConstMethod << MD; |
| 11443 | DiagnosticEmitted = true; |
| 11444 | } |
| 11445 | S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) |
| 11446 | << ConstMethod << MD << MD->getSourceRange(); |
| 11447 | } |
| 11448 | } |
| 11449 | } |
| 11450 | } |
| 11451 | |
| 11452 | if (DiagnosticEmitted) |
| 11453 | return; |
| 11454 | |
| 11455 | // Can't determine a more specific message, so display the generic error. |
| 11456 | S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; |
| 11457 | } |
| 11458 | |
| 11459 | enum OriginalExprKind { |
| 11460 | OEK_Variable, |
| 11461 | OEK_Member, |
| 11462 | OEK_LValue |
| 11463 | }; |
| 11464 | |
| 11465 | static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, |
| 11466 | const RecordType *Ty, |
| 11467 | SourceLocation Loc, SourceRange Range, |
| 11468 | OriginalExprKind OEK, |
| 11469 | bool &DiagnosticEmitted) { |
| 11470 | std::vector<const RecordType *> RecordTypeList; |
| 11471 | RecordTypeList.push_back(Ty); |
| 11472 | unsigned NextToCheckIndex = 0; |
| 11473 | // We walk the record hierarchy breadth-first to ensure that we print |
| 11474 | // diagnostics in field nesting order. |
| 11475 | while (RecordTypeList.size() > NextToCheckIndex) { |
| 11476 | bool IsNested = NextToCheckIndex > 0; |
| 11477 | for (const FieldDecl *Field : |
| 11478 | RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { |
| 11479 | // First, check every field for constness. |
| 11480 | QualType FieldTy = Field->getType(); |
| 11481 | if (FieldTy.isConstQualified()) { |
| 11482 | if (!DiagnosticEmitted) { |
| 11483 | S.Diag(Loc, diag::err_typecheck_assign_const) |
| 11484 | << Range << NestedConstMember << OEK << VD |
| 11485 | << IsNested << Field; |
| 11486 | DiagnosticEmitted = true; |
| 11487 | } |
| 11488 | S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) |
| 11489 | << NestedConstMember << IsNested << Field |
| 11490 | << FieldTy << Field->getSourceRange(); |
| 11491 | } |
| 11492 | |
| 11493 | // Then we append it to the list to check next in order. |
| 11494 | FieldTy = FieldTy.getCanonicalType(); |
| 11495 | if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { |
| 11496 | if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) |
| 11497 | RecordTypeList.push_back(FieldRecTy); |
| 11498 | } |
| 11499 | } |
| 11500 | ++NextToCheckIndex; |
| 11501 | } |
| 11502 | } |
| 11503 | |
| 11504 | /// Emit an error for the case where a record we are trying to assign to has a |
| 11505 | /// const-qualified field somewhere in its hierarchy. |
| 11506 | static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, |
| 11507 | SourceLocation Loc) { |
| 11508 | QualType Ty = E->getType(); |
| 11509 | assert(Ty->isRecordType() && "lvalue was not record?" ); |
| 11510 | SourceRange Range = E->getSourceRange(); |
| 11511 | const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); |
| 11512 | bool DiagEmitted = false; |
| 11513 | |
| 11514 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) |
| 11515 | DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, |
| 11516 | Range, OEK_Member, DiagEmitted); |
| 11517 | else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) |
| 11518 | DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, |
| 11519 | Range, OEK_Variable, DiagEmitted); |
| 11520 | else |
| 11521 | DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, |
| 11522 | Range, OEK_LValue, DiagEmitted); |
| 11523 | if (!DiagEmitted) |
| 11524 | DiagnoseConstAssignment(S, E, Loc); |
| 11525 | } |
| 11526 | |
| 11527 | /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, |
| 11528 | /// emit an error and return true. If so, return false. |
| 11529 | static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { |
| 11530 | assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); |
| 11531 | |
| 11532 | S.CheckShadowingDeclModification(E, Loc); |
| 11533 | |
| 11534 | SourceLocation OrigLoc = Loc; |
| 11535 | Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, |
| 11536 | &Loc); |
| 11537 | if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) |
| 11538 | IsLV = Expr::MLV_InvalidMessageExpression; |
| 11539 | if (IsLV == Expr::MLV_Valid) |
| 11540 | return false; |
| 11541 | |
| 11542 | unsigned DiagID = 0; |
| 11543 | bool NeedType = false; |
| 11544 | switch (IsLV) { // C99 6.5.16p2 |
| 11545 | case Expr::MLV_ConstQualified: |
| 11546 | // Use a specialized diagnostic when we're assigning to an object |
| 11547 | // from an enclosing function or block. |
| 11548 | if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { |
| 11549 | if (NCCK == NCCK_Block) |
| 11550 | DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; |
| 11551 | else |
| 11552 | DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; |
| 11553 | break; |
| 11554 | } |
| 11555 | |
| 11556 | // In ARC, use some specialized diagnostics for occasions where we |
| 11557 | // infer 'const'. These are always pseudo-strong variables. |
| 11558 | if (S.getLangOpts().ObjCAutoRefCount) { |
| 11559 | DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); |
| 11560 | if (declRef && isa<VarDecl>(declRef->getDecl())) { |
| 11561 | VarDecl *var = cast<VarDecl>(declRef->getDecl()); |
| 11562 | |
| 11563 | // Use the normal diagnostic if it's pseudo-__strong but the |
| 11564 | // user actually wrote 'const'. |
| 11565 | if (var->isARCPseudoStrong() && |
| 11566 | (!var->getTypeSourceInfo() || |
| 11567 | !var->getTypeSourceInfo()->getType().isConstQualified())) { |
| 11568 | // There are three pseudo-strong cases: |
| 11569 | // - self |
| 11570 | ObjCMethodDecl *method = S.getCurMethodDecl(); |
| 11571 | if (method && var == method->getSelfDecl()) { |
| 11572 | DiagID = method->isClassMethod() |
| 11573 | ? diag::err_typecheck_arc_assign_self_class_method |
| 11574 | : diag::err_typecheck_arc_assign_self; |
| 11575 | |
| 11576 | // - Objective-C externally_retained attribute. |
| 11577 | } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || |
| 11578 | isa<ParmVarDecl>(var)) { |
| 11579 | DiagID = diag::err_typecheck_arc_assign_externally_retained; |
| 11580 | |
| 11581 | // - fast enumeration variables |
| 11582 | } else { |
| 11583 | DiagID = diag::err_typecheck_arr_assign_enumeration; |
| 11584 | } |
| 11585 | |
| 11586 | SourceRange Assign; |
| 11587 | if (Loc != OrigLoc) |
| 11588 | Assign = SourceRange(OrigLoc, OrigLoc); |
| 11589 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
| 11590 | // We need to preserve the AST regardless, so migration tool |
| 11591 | // can do its job. |
| 11592 | return false; |
| 11593 | } |
| 11594 | } |
| 11595 | } |
| 11596 | |
| 11597 | // If none of the special cases above are triggered, then this is a |
| 11598 | // simple const assignment. |
| 11599 | if (DiagID == 0) { |
| 11600 | DiagnoseConstAssignment(S, E, Loc); |
| 11601 | return true; |
| 11602 | } |
| 11603 | |
| 11604 | break; |
| 11605 | case Expr::MLV_ConstAddrSpace: |
| 11606 | DiagnoseConstAssignment(S, E, Loc); |
| 11607 | return true; |
| 11608 | case Expr::MLV_ConstQualifiedField: |
| 11609 | DiagnoseRecursiveConstFields(S, E, Loc); |
| 11610 | return true; |
| 11611 | case Expr::MLV_ArrayType: |
| 11612 | case Expr::MLV_ArrayTemporary: |
| 11613 | DiagID = diag::err_typecheck_array_not_modifiable_lvalue; |
| 11614 | NeedType = true; |
| 11615 | break; |
| 11616 | case Expr::MLV_NotObjectType: |
| 11617 | DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; |
| 11618 | NeedType = true; |
| 11619 | break; |
| 11620 | case Expr::MLV_LValueCast: |
| 11621 | DiagID = diag::err_typecheck_lvalue_casts_not_supported; |
| 11622 | break; |
| 11623 | case Expr::MLV_Valid: |
| 11624 | llvm_unreachable("did not take early return for MLV_Valid" ); |
| 11625 | case Expr::MLV_InvalidExpression: |
| 11626 | case Expr::MLV_MemberFunction: |
| 11627 | case Expr::MLV_ClassTemporary: |
| 11628 | DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; |
| 11629 | break; |
| 11630 | case Expr::MLV_IncompleteType: |
| 11631 | case Expr::MLV_IncompleteVoidType: |
| 11632 | return S.RequireCompleteType(Loc, E->getType(), |
| 11633 | diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); |
| 11634 | case Expr::MLV_DuplicateVectorComponents: |
| 11635 | DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; |
| 11636 | break; |
| 11637 | case Expr::MLV_NoSetterProperty: |
| 11638 | llvm_unreachable("readonly properties should be processed differently" ); |
| 11639 | case Expr::MLV_InvalidMessageExpression: |
| 11640 | DiagID = diag::err_readonly_message_assignment; |
| 11641 | break; |
| 11642 | case Expr::MLV_SubObjCPropertySetting: |
| 11643 | DiagID = diag::err_no_subobject_property_setting; |
| 11644 | break; |
| 11645 | } |
| 11646 | |
| 11647 | SourceRange Assign; |
| 11648 | if (Loc != OrigLoc) |
| 11649 | Assign = SourceRange(OrigLoc, OrigLoc); |
| 11650 | if (NeedType) |
| 11651 | S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; |
| 11652 | else |
| 11653 | S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; |
| 11654 | return true; |
| 11655 | } |
| 11656 | |
| 11657 | static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, |
| 11658 | SourceLocation Loc, |
| 11659 | Sema &Sema) { |
| 11660 | if (Sema.inTemplateInstantiation()) |
| 11661 | return; |
| 11662 | if (Sema.isUnevaluatedContext()) |
| 11663 | return; |
| 11664 | if (Loc.isInvalid() || Loc.isMacroID()) |
| 11665 | return; |
| 11666 | if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) |
| 11667 | return; |
| 11668 | |
| 11669 | // C / C++ fields |
| 11670 | MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); |
| 11671 | MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); |
| 11672 | if (ML && MR) { |
| 11673 | if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) |
| 11674 | return; |
| 11675 | const ValueDecl *LHSDecl = |
| 11676 | cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); |
| 11677 | const ValueDecl *RHSDecl = |
| 11678 | cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); |
| 11679 | if (LHSDecl != RHSDecl) |
| 11680 | return; |
| 11681 | if (LHSDecl->getType().isVolatileQualified()) |
| 11682 | return; |
| 11683 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
| 11684 | if (RefTy->getPointeeType().isVolatileQualified()) |
| 11685 | return; |
| 11686 | |
| 11687 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; |
| 11688 | } |
| 11689 | |
| 11690 | // Objective-C instance variables |
| 11691 | ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); |
| 11692 | ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); |
| 11693 | if (OL && OR && OL->getDecl() == OR->getDecl()) { |
| 11694 | DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); |
| 11695 | DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); |
| 11696 | if (RL && RR && RL->getDecl() == RR->getDecl()) |
| 11697 | Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; |
| 11698 | } |
| 11699 | } |
| 11700 | |
| 11701 | // C99 6.5.16.1 |
| 11702 | QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, |
| 11703 | SourceLocation Loc, |
| 11704 | QualType CompoundType) { |
| 11705 | assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); |
| 11706 | |
| 11707 | // Verify that LHS is a modifiable lvalue, and emit error if not. |
| 11708 | if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) |
| 11709 | return QualType(); |
| 11710 | |
| 11711 | QualType LHSType = LHSExpr->getType(); |
| 11712 | QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : |
| 11713 | CompoundType; |
| 11714 | // OpenCL v1.2 s6.1.1.1 p2: |
| 11715 | // The half data type can only be used to declare a pointer to a buffer that |
| 11716 | // contains half values |
| 11717 | if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16" ) && |
| 11718 | LHSType->isHalfType()) { |
| 11719 | Diag(Loc, diag::err_opencl_half_load_store) << 1 |
| 11720 | << LHSType.getUnqualifiedType(); |
| 11721 | return QualType(); |
| 11722 | } |
| 11723 | |
| 11724 | AssignConvertType ConvTy; |
| 11725 | if (CompoundType.isNull()) { |
| 11726 | Expr *RHSCheck = RHS.get(); |
| 11727 | |
| 11728 | CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); |
| 11729 | |
| 11730 | QualType LHSTy(LHSType); |
| 11731 | ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); |
| 11732 | if (RHS.isInvalid()) |
| 11733 | return QualType(); |
| 11734 | // Special case of NSObject attributes on c-style pointer types. |
| 11735 | if (ConvTy == IncompatiblePointer && |
| 11736 | ((Context.isObjCNSObjectType(LHSType) && |
| 11737 | RHSType->isObjCObjectPointerType()) || |
| 11738 | (Context.isObjCNSObjectType(RHSType) && |
| 11739 | LHSType->isObjCObjectPointerType()))) |
| 11740 | ConvTy = Compatible; |
| 11741 | |
| 11742 | if (ConvTy == Compatible && |
| 11743 | LHSType->isObjCObjectType()) |
| 11744 | Diag(Loc, diag::err_objc_object_assignment) |
| 11745 | << LHSType; |
| 11746 | |
| 11747 | // If the RHS is a unary plus or minus, check to see if they = and + are |
| 11748 | // right next to each other. If so, the user may have typo'd "x =+ 4" |
| 11749 | // instead of "x += 4". |
| 11750 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) |
| 11751 | RHSCheck = ICE->getSubExpr(); |
| 11752 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { |
| 11753 | if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && |
| 11754 | Loc.isFileID() && UO->getOperatorLoc().isFileID() && |
| 11755 | // Only if the two operators are exactly adjacent. |
| 11756 | Loc.getLocWithOffset(1) == UO->getOperatorLoc() && |
| 11757 | // And there is a space or other character before the subexpr of the |
| 11758 | // unary +/-. We don't want to warn on "x=-1". |
| 11759 | Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && |
| 11760 | UO->getSubExpr()->getBeginLoc().isFileID()) { |
| 11761 | Diag(Loc, diag::warn_not_compound_assign) |
| 11762 | << (UO->getOpcode() == UO_Plus ? "+" : "-" ) |
| 11763 | << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); |
| 11764 | } |
| 11765 | } |
| 11766 | |
| 11767 | if (ConvTy == Compatible) { |
| 11768 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { |
| 11769 | // Warn about retain cycles where a block captures the LHS, but |
| 11770 | // not if the LHS is a simple variable into which the block is |
| 11771 | // being stored...unless that variable can be captured by reference! |
| 11772 | const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); |
| 11773 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); |
| 11774 | if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) |
| 11775 | checkRetainCycles(LHSExpr, RHS.get()); |
| 11776 | } |
| 11777 | |
| 11778 | if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || |
| 11779 | LHSType.isNonWeakInMRRWithObjCWeak(Context)) { |
| 11780 | // It is safe to assign a weak reference into a strong variable. |
| 11781 | // Although this code can still have problems: |
| 11782 | // id x = self.weakProp; |
| 11783 | // id y = self.weakProp; |
| 11784 | // we do not warn to warn spuriously when 'x' and 'y' are on separate |
| 11785 | // paths through the function. This should be revisited if |
| 11786 | // -Wrepeated-use-of-weak is made flow-sensitive. |
| 11787 | // For ObjCWeak only, we do not warn if the assign is to a non-weak |
| 11788 | // variable, which will be valid for the current autorelease scope. |
| 11789 | if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, |
| 11790 | RHS.get()->getBeginLoc())) |
| 11791 | getCurFunction()->markSafeWeakUse(RHS.get()); |
| 11792 | |
| 11793 | } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { |
| 11794 | checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); |
| 11795 | } |
| 11796 | } |
| 11797 | } else { |
| 11798 | // Compound assignment "x += y" |
| 11799 | ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); |
| 11800 | } |
| 11801 | |
| 11802 | if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, |
| 11803 | RHS.get(), AA_Assigning)) |
| 11804 | return QualType(); |
| 11805 | |
| 11806 | CheckForNullPointerDereference(*this, LHSExpr); |
| 11807 | |
| 11808 | // C99 6.5.16p3: The type of an assignment expression is the type of the |
| 11809 | // left operand unless the left operand has qualified type, in which case |
| 11810 | // it is the unqualified version of the type of the left operand. |
| 11811 | // C99 6.5.16.1p2: In simple assignment, the value of the right operand |
| 11812 | // is converted to the type of the assignment expression (above). |
| 11813 | // C++ 5.17p1: the type of the assignment expression is that of its left |
| 11814 | // operand. |
| 11815 | return (getLangOpts().CPlusPlus |
| 11816 | ? LHSType : LHSType.getUnqualifiedType()); |
| 11817 | } |
| 11818 | |
| 11819 | // Only ignore explicit casts to void. |
| 11820 | static bool IgnoreCommaOperand(const Expr *E) { |
| 11821 | E = E->IgnoreParens(); |
| 11822 | |
| 11823 | if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { |
| 11824 | if (CE->getCastKind() == CK_ToVoid) { |
| 11825 | return true; |
| 11826 | } |
| 11827 | |
| 11828 | // static_cast<void> on a dependent type will not show up as CK_ToVoid. |
| 11829 | if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && |
| 11830 | CE->getSubExpr()->getType()->isDependentType()) { |
| 11831 | return true; |
| 11832 | } |
| 11833 | } |
| 11834 | |
| 11835 | return false; |
| 11836 | } |
| 11837 | |
| 11838 | // Look for instances where it is likely the comma operator is confused with |
| 11839 | // another operator. There is a whitelist of acceptable expressions for the |
| 11840 | // left hand side of the comma operator, otherwise emit a warning. |
| 11841 | void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { |
| 11842 | // No warnings in macros |
| 11843 | if (Loc.isMacroID()) |
| 11844 | return; |
| 11845 | |
| 11846 | // Don't warn in template instantiations. |
| 11847 | if (inTemplateInstantiation()) |
| 11848 | return; |
| 11849 | |
| 11850 | // Scope isn't fine-grained enough to whitelist the specific cases, so |
| 11851 | // instead, skip more than needed, then call back into here with the |
| 11852 | // CommaVisitor in SemaStmt.cpp. |
| 11853 | // The whitelisted locations are the initialization and increment portions |
| 11854 | // of a for loop. The additional checks are on the condition of |
| 11855 | // if statements, do/while loops, and for loops. |
| 11856 | // Differences in scope flags for C89 mode requires the extra logic. |
| 11857 | const unsigned ForIncrementFlags = |
| 11858 | getLangOpts().C99 || getLangOpts().CPlusPlus |
| 11859 | ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope |
| 11860 | : Scope::ContinueScope | Scope::BreakScope; |
| 11861 | const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; |
| 11862 | const unsigned ScopeFlags = getCurScope()->getFlags(); |
| 11863 | if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || |
| 11864 | (ScopeFlags & ForInitFlags) == ForInitFlags) |
| 11865 | return; |
| 11866 | |
| 11867 | // If there are multiple comma operators used together, get the RHS of the |
| 11868 | // of the comma operator as the LHS. |
| 11869 | while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { |
| 11870 | if (BO->getOpcode() != BO_Comma) |
| 11871 | break; |
| 11872 | LHS = BO->getRHS(); |
| 11873 | } |
| 11874 | |
| 11875 | // Only allow some expressions on LHS to not warn. |
| 11876 | if (IgnoreCommaOperand(LHS)) |
| 11877 | return; |
| 11878 | |
| 11879 | Diag(Loc, diag::warn_comma_operator); |
| 11880 | Diag(LHS->getBeginLoc(), diag::note_cast_to_void) |
| 11881 | << LHS->getSourceRange() |
| 11882 | << FixItHint::CreateInsertion(LHS->getBeginLoc(), |
| 11883 | LangOpts.CPlusPlus ? "static_cast<void>(" |
| 11884 | : "(void)(" ) |
| 11885 | << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), |
| 11886 | ")" ); |
| 11887 | } |
| 11888 | |
| 11889 | // C99 6.5.17 |
| 11890 | static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, |
| 11891 | SourceLocation Loc) { |
| 11892 | LHS = S.CheckPlaceholderExpr(LHS.get()); |
| 11893 | RHS = S.CheckPlaceholderExpr(RHS.get()); |
| 11894 | if (LHS.isInvalid() || RHS.isInvalid()) |
| 11895 | return QualType(); |
| 11896 | |
| 11897 | // C's comma performs lvalue conversion (C99 6.3.2.1) on both its |
| 11898 | // operands, but not unary promotions. |
| 11899 | // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). |
| 11900 | |
| 11901 | // So we treat the LHS as a ignored value, and in C++ we allow the |
| 11902 | // containing site to determine what should be done with the RHS. |
| 11903 | LHS = S.IgnoredValueConversions(LHS.get()); |
| 11904 | if (LHS.isInvalid()) |
| 11905 | return QualType(); |
| 11906 | |
| 11907 | S.DiagnoseUnusedExprResult(LHS.get()); |
| 11908 | |
| 11909 | if (!S.getLangOpts().CPlusPlus) { |
| 11910 | RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); |
| 11911 | if (RHS.isInvalid()) |
| 11912 | return QualType(); |
| 11913 | if (!RHS.get()->getType()->isVoidType()) |
| 11914 | S.RequireCompleteType(Loc, RHS.get()->getType(), |
| 11915 | diag::err_incomplete_type); |
| 11916 | } |
| 11917 | |
| 11918 | if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) |
| 11919 | S.DiagnoseCommaOperator(LHS.get(), Loc); |
| 11920 | |
| 11921 | return RHS.get()->getType(); |
| 11922 | } |
| 11923 | |
| 11924 | /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine |
| 11925 | /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. |
| 11926 | static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, |
| 11927 | ExprValueKind &VK, |
| 11928 | ExprObjectKind &OK, |
| 11929 | SourceLocation OpLoc, |
| 11930 | bool IsInc, bool IsPrefix) { |
| 11931 | if (Op->isTypeDependent()) |
| 11932 | return S.Context.DependentTy; |
| 11933 | |
| 11934 | QualType ResType = Op->getType(); |
| 11935 | // Atomic types can be used for increment / decrement where the non-atomic |
| 11936 | // versions can, so ignore the _Atomic() specifier for the purpose of |
| 11937 | // checking. |
| 11938 | if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) |
| 11939 | ResType = ResAtomicType->getValueType(); |
| 11940 | |
| 11941 | assert(!ResType.isNull() && "no type for increment/decrement expression" ); |
| 11942 | |
| 11943 | if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { |
| 11944 | // Decrement of bool is not allowed. |
| 11945 | if (!IsInc) { |
| 11946 | S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); |
| 11947 | return QualType(); |
| 11948 | } |
| 11949 | // Increment of bool sets it to true, but is deprecated. |
| 11950 | S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool |
| 11951 | : diag::warn_increment_bool) |
| 11952 | << Op->getSourceRange(); |
| 11953 | } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { |
| 11954 | // Error on enum increments and decrements in C++ mode |
| 11955 | S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; |
| 11956 | return QualType(); |
| 11957 | } else if (ResType->isRealType()) { |
| 11958 | // OK! |
| 11959 | } else if (ResType->isPointerType()) { |
| 11960 | // C99 6.5.2.4p2, 6.5.6p2 |
| 11961 | if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) |
| 11962 | return QualType(); |
| 11963 | } else if (ResType->isObjCObjectPointerType()) { |
| 11964 | // On modern runtimes, ObjC pointer arithmetic is forbidden. |
| 11965 | // Otherwise, we just need a complete type. |
| 11966 | if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || |
| 11967 | checkArithmeticOnObjCPointer(S, OpLoc, Op)) |
| 11968 | return QualType(); |
| 11969 | } else if (ResType->isAnyComplexType()) { |
| 11970 | // C99 does not support ++/-- on complex types, we allow as an extension. |
| 11971 | S.Diag(OpLoc, diag::ext_integer_increment_complex) |
| 11972 | << ResType << Op->getSourceRange(); |
| 11973 | } else if (ResType->isPlaceholderType()) { |
| 11974 | ExprResult PR = S.CheckPlaceholderExpr(Op); |
| 11975 | if (PR.isInvalid()) return QualType(); |
| 11976 | return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, |
| 11977 | IsInc, IsPrefix); |
| 11978 | } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { |
| 11979 | // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) |
| 11980 | } else if (S.getLangOpts().ZVector && ResType->isVectorType() && |
| 11981 | (ResType->getAs<VectorType>()->getVectorKind() != |
| 11982 | VectorType::AltiVecBool)) { |
| 11983 | // The z vector extensions allow ++ and -- for non-bool vectors. |
| 11984 | } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && |
| 11985 | ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { |
| 11986 | // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. |
| 11987 | } else { |
| 11988 | S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) |
| 11989 | << ResType << int(IsInc) << Op->getSourceRange(); |
| 11990 | return QualType(); |
| 11991 | } |
| 11992 | // At this point, we know we have a real, complex or pointer type. |
| 11993 | // Now make sure the operand is a modifiable lvalue. |
| 11994 | if (CheckForModifiableLvalue(Op, OpLoc, S)) |
| 11995 | return QualType(); |
| 11996 | // In C++, a prefix increment is the same type as the operand. Otherwise |
| 11997 | // (in C or with postfix), the increment is the unqualified type of the |
| 11998 | // operand. |
| 11999 | if (IsPrefix && S.getLangOpts().CPlusPlus) { |
| 12000 | VK = VK_LValue; |
| 12001 | OK = Op->getObjectKind(); |
| 12002 | return ResType; |
| 12003 | } else { |
| 12004 | VK = VK_RValue; |
| 12005 | return ResType.getUnqualifiedType(); |
| 12006 | } |
| 12007 | } |
| 12008 | |
| 12009 | |
| 12010 | /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). |
| 12011 | /// This routine allows us to typecheck complex/recursive expressions |
| 12012 | /// where the declaration is needed for type checking. We only need to |
| 12013 | /// handle cases when the expression references a function designator |
| 12014 | /// or is an lvalue. Here are some examples: |
| 12015 | /// - &(x) => x |
| 12016 | /// - &*****f => f for f a function designator. |
| 12017 | /// - &s.xx => s |
| 12018 | /// - &s.zz[1].yy -> s, if zz is an array |
| 12019 | /// - *(x + 1) -> x, if x is an array |
| 12020 | /// - &"123"[2] -> 0 |
| 12021 | /// - & __real__ x -> x |
| 12022 | static ValueDecl *getPrimaryDecl(Expr *E) { |
| 12023 | switch (E->getStmtClass()) { |
| 12024 | case Stmt::DeclRefExprClass: |
| 12025 | return cast<DeclRefExpr>(E)->getDecl(); |
| 12026 | case Stmt::MemberExprClass: |
| 12027 | // If this is an arrow operator, the address is an offset from |
| 12028 | // the base's value, so the object the base refers to is |
| 12029 | // irrelevant. |
| 12030 | if (cast<MemberExpr>(E)->isArrow()) |
| 12031 | return nullptr; |
| 12032 | // Otherwise, the expression refers to a part of the base |
| 12033 | return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); |
| 12034 | case Stmt::ArraySubscriptExprClass: { |
| 12035 | // FIXME: This code shouldn't be necessary! We should catch the implicit |
| 12036 | // promotion of register arrays earlier. |
| 12037 | Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); |
| 12038 | if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { |
| 12039 | if (ICE->getSubExpr()->getType()->isArrayType()) |
| 12040 | return getPrimaryDecl(ICE->getSubExpr()); |
| 12041 | } |
| 12042 | return nullptr; |
| 12043 | } |
| 12044 | case Stmt::UnaryOperatorClass: { |
| 12045 | UnaryOperator *UO = cast<UnaryOperator>(E); |
| 12046 | |
| 12047 | switch(UO->getOpcode()) { |
| 12048 | case UO_Real: |
| 12049 | case UO_Imag: |
| 12050 | case UO_Extension: |
| 12051 | return getPrimaryDecl(UO->getSubExpr()); |
| 12052 | default: |
| 12053 | return nullptr; |
| 12054 | } |
| 12055 | } |
| 12056 | case Stmt::ParenExprClass: |
| 12057 | return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); |
| 12058 | case Stmt::ImplicitCastExprClass: |
| 12059 | // If the result of an implicit cast is an l-value, we care about |
| 12060 | // the sub-expression; otherwise, the result here doesn't matter. |
| 12061 | return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); |
| 12062 | default: |
| 12063 | return nullptr; |
| 12064 | } |
| 12065 | } |
| 12066 | |
| 12067 | namespace { |
| 12068 | enum { |
| 12069 | AO_Bit_Field = 0, |
| 12070 | AO_Vector_Element = 1, |
| 12071 | AO_Property_Expansion = 2, |
| 12072 | AO_Register_Variable = 3, |
| 12073 | AO_No_Error = 4 |
| 12074 | }; |
| 12075 | } |
| 12076 | /// Diagnose invalid operand for address of operations. |
| 12077 | /// |
| 12078 | /// \param Type The type of operand which cannot have its address taken. |
| 12079 | static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, |
| 12080 | Expr *E, unsigned Type) { |
| 12081 | S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); |
| 12082 | } |
| 12083 | |
| 12084 | static ASTContext::PointerInterpretationKind |
| 12085 | pointerKindForBaseExpr(const ASTContext &Context, const Expr *Base, bool WasMemberExpr = false) { |
| 12086 | if (auto *mr = dyn_cast<MemberExpr>(Base)) |
| 12087 | return pointerKindForBaseExpr(Context, mr->getBase(), true); |
| 12088 | else if (auto *as = dyn_cast<ArraySubscriptExpr>(Base)) |
| 12089 | // We need IgnoreImpCasts() here to strip the ArrayToPointerDecay |
| 12090 | return pointerKindForBaseExpr(Context, as->getBase()->IgnoreImpCasts(), true); |
| 12091 | |
| 12092 | // If we are just taking the address of something that happens to be a |
| 12093 | // capability we should not infer that the result is a capability. This only |
| 12094 | // applies if there is a least one level of MemberExpr/ArraySubscriptExpr |
| 12095 | // For example the following should be an error in the hybrid ABI: |
| 12096 | // void * __capability b; |
| 12097 | // void *__capability *__capability c = &b; |
| 12098 | if (!WasMemberExpr) |
| 12099 | return ASTContext::PIK_Default; |
| 12100 | // If the basetype is __uintcap_t we don't want to treat the result as a |
| 12101 | // capability (such as in uintcap_t foo; return &foo;) |
| 12102 | if (Base->getType()->isCHERICapabilityType(Context, /*IncludeIntCap=*/false)) |
| 12103 | return ASTContext::PIK_Capability; |
| 12104 | return ASTContext::PIK_Default; |
| 12105 | } |
| 12106 | |
| 12107 | /// CheckAddressOfOperand - The operand of & must be either a function |
| 12108 | /// designator or an lvalue designating an object. If it is an lvalue, the |
| 12109 | /// object cannot be declared with storage class register or be a bit field. |
| 12110 | /// Note: The usual conversions are *not* applied to the operand of the & |
| 12111 | /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. |
| 12112 | /// In C++, the operand might be an overloaded function name, in which case |
| 12113 | /// we allow the '&' but retain the overloaded-function type. |
| 12114 | QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { |
| 12115 | if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ |
| 12116 | if (PTy->getKind() == BuiltinType::Overload) { |
| 12117 | Expr *E = OrigOp.get()->IgnoreParens(); |
| 12118 | if (!isa<OverloadExpr>(E)) { |
| 12119 | assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); |
| 12120 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) |
| 12121 | << OrigOp.get()->getSourceRange(); |
| 12122 | return QualType(); |
| 12123 | } |
| 12124 | |
| 12125 | OverloadExpr *Ovl = cast<OverloadExpr>(E); |
| 12126 | if (isa<UnresolvedMemberExpr>(Ovl)) |
| 12127 | if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { |
| 12128 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) |
| 12129 | << OrigOp.get()->getSourceRange(); |
| 12130 | return QualType(); |
| 12131 | } |
| 12132 | |
| 12133 | return Context.OverloadTy; |
| 12134 | } |
| 12135 | |
| 12136 | if (PTy->getKind() == BuiltinType::UnknownAny) |
| 12137 | return Context.UnknownAnyTy; |
| 12138 | |
| 12139 | if (PTy->getKind() == BuiltinType::BoundMember) { |
| 12140 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) |
| 12141 | << OrigOp.get()->getSourceRange(); |
| 12142 | return QualType(); |
| 12143 | } |
| 12144 | |
| 12145 | OrigOp = CheckPlaceholderExpr(OrigOp.get()); |
| 12146 | if (OrigOp.isInvalid()) return QualType(); |
| 12147 | } |
| 12148 | |
| 12149 | if (OrigOp.get()->isTypeDependent()) |
| 12150 | return Context.DependentTy; |
| 12151 | |
| 12152 | assert(!OrigOp.get()->getType()->isPlaceholderType()); |
| 12153 | |
| 12154 | // Make sure to ignore parentheses in subsequent checks |
| 12155 | Expr *op = OrigOp.get()->IgnoreParens(); |
| 12156 | |
| 12157 | // In OpenCL captures for blocks called as lambda functions |
| 12158 | // are located in the private address space. Blocks used in |
| 12159 | // enqueue_kernel can be located in a different address space |
| 12160 | // depending on a vendor implementation. Thus preventing |
| 12161 | // taking an address of the capture to avoid invalid AS casts. |
| 12162 | if (LangOpts.OpenCL) { |
| 12163 | auto* VarRef = dyn_cast<DeclRefExpr>(op); |
| 12164 | if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { |
| 12165 | Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); |
| 12166 | return QualType(); |
| 12167 | } |
| 12168 | } |
| 12169 | |
| 12170 | if (getLangOpts().C99) { |
| 12171 | // Implement C99-only parts of addressof rules. |
| 12172 | if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { |
| 12173 | if (uOp->getOpcode() == UO_Deref) |
| 12174 | // Per C99 6.5.3.2, the address of a deref always returns a valid result |
| 12175 | // (assuming the deref expression is valid). |
| 12176 | return uOp->getSubExpr()->getType(); |
| 12177 | } |
| 12178 | // Technically, there should be a check for array subscript |
| 12179 | // expressions here, but the result of one is always an lvalue anyway. |
| 12180 | } |
| 12181 | ValueDecl *dcl = getPrimaryDecl(op); |
| 12182 | |
| 12183 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) |
| 12184 | if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, |
| 12185 | op->getBeginLoc())) |
| 12186 | return QualType(); |
| 12187 | |
| 12188 | Expr::LValueClassification lval = op->ClassifyLValue(Context); |
| 12189 | unsigned AddressOfError = AO_No_Error; |
| 12190 | |
| 12191 | if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { |
| 12192 | bool sfinae = (bool)isSFINAEContext(); |
| 12193 | Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary |
| 12194 | : diag::ext_typecheck_addrof_temporary) |
| 12195 | << op->getType() << op->getSourceRange(); |
| 12196 | if (sfinae) |
| 12197 | return QualType(); |
| 12198 | // Materialize the temporary as an lvalue so that we can take its address. |
| 12199 | OrigOp = op = |
| 12200 | CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); |
| 12201 | } else if (isa<ObjCSelectorExpr>(op)) { |
| 12202 | return Context.getPointerType(op->getType()); |
| 12203 | } else if (lval == Expr::LV_MemberFunction) { |
| 12204 | // If it's an instance method, make a member pointer. |
| 12205 | // The expression must have exactly the form &A::foo. |
| 12206 | |
| 12207 | // If the underlying expression isn't a decl ref, give up. |
| 12208 | if (!isa<DeclRefExpr>(op)) { |
| 12209 | Diag(OpLoc, diag::err_invalid_form_pointer_member_function) |
| 12210 | << OrigOp.get()->getSourceRange(); |
| 12211 | return QualType(); |
| 12212 | } |
| 12213 | DeclRefExpr *DRE = cast<DeclRefExpr>(op); |
| 12214 | CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); |
| 12215 | |
| 12216 | // The id-expression was parenthesized. |
| 12217 | if (OrigOp.get() != DRE) { |
| 12218 | Diag(OpLoc, diag::err_parens_pointer_member_function) |
| 12219 | << OrigOp.get()->getSourceRange(); |
| 12220 | |
| 12221 | // The method was named without a qualifier. |
| 12222 | } else if (!DRE->getQualifier()) { |
| 12223 | if (MD->getParent()->getName().empty()) |
| 12224 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) |
| 12225 | << op->getSourceRange(); |
| 12226 | else { |
| 12227 | SmallString<32> Str; |
| 12228 | StringRef Qual = (MD->getParent()->getName() + "::" ).toStringRef(Str); |
| 12229 | Diag(OpLoc, diag::err_unqualified_pointer_member_function) |
| 12230 | << op->getSourceRange() |
| 12231 | << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); |
| 12232 | } |
| 12233 | } |
| 12234 | |
| 12235 | // Taking the address of a dtor is illegal per C++ [class.dtor]p2. |
| 12236 | if (isa<CXXDestructorDecl>(MD)) |
| 12237 | Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); |
| 12238 | |
| 12239 | QualType MPTy = Context.getMemberPointerType( |
| 12240 | op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); |
| 12241 | // Under the MS ABI, lock down the inheritance model now. |
| 12242 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 12243 | (void)isCompleteType(OpLoc, MPTy); |
| 12244 | return MPTy; |
| 12245 | } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { |
| 12246 | // C99 6.5.3.2p1 |
| 12247 | // The operand must be either an l-value or a function designator |
| 12248 | if (!op->getType()->isFunctionType()) { |
| 12249 | // Use a special diagnostic for loads from property references. |
| 12250 | if (isa<PseudoObjectExpr>(op)) { |
| 12251 | AddressOfError = AO_Property_Expansion; |
| 12252 | } else { |
| 12253 | Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) |
| 12254 | << op->getType() << op->getSourceRange(); |
| 12255 | return QualType(); |
| 12256 | } |
| 12257 | } |
| 12258 | } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 |
| 12259 | // The operand cannot be a bit-field |
| 12260 | AddressOfError = AO_Bit_Field; |
| 12261 | } else if (op->getObjectKind() == OK_VectorComponent) { |
| 12262 | // The operand cannot be an element of a vector |
| 12263 | AddressOfError = AO_Vector_Element; |
| 12264 | } else if (dcl) { // C99 6.5.3.2p1 |
| 12265 | // We have an lvalue with a decl. Make sure the decl is not declared |
| 12266 | // with the register storage-class specifier. |
| 12267 | if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { |
| 12268 | // in C++ it is not error to take address of a register |
| 12269 | // variable (c++03 7.1.1P3) |
| 12270 | if (vd->getStorageClass() == SC_Register && |
| 12271 | !getLangOpts().CPlusPlus) { |
| 12272 | AddressOfError = AO_Register_Variable; |
| 12273 | } |
| 12274 | } else if (isa<MSPropertyDecl>(dcl)) { |
| 12275 | AddressOfError = AO_Property_Expansion; |
| 12276 | } else if (isa<FunctionTemplateDecl>(dcl)) { |
| 12277 | return Context.OverloadTy; |
| 12278 | } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { |
| 12279 | // Okay: we can take the address of a field. |
| 12280 | // Could be a pointer to member, though, if there is an explicit |
| 12281 | // scope qualifier for the class. |
| 12282 | if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { |
| 12283 | DeclContext *Ctx = dcl->getDeclContext(); |
| 12284 | if (Ctx && Ctx->isRecord()) { |
| 12285 | if (dcl->getType()->isReferenceType()) { |
| 12286 | Diag(OpLoc, |
| 12287 | diag::err_cannot_form_pointer_to_member_of_reference_type) |
| 12288 | << dcl->getDeclName() << dcl->getType(); |
| 12289 | return QualType(); |
| 12290 | } |
| 12291 | |
| 12292 | while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) |
| 12293 | Ctx = Ctx->getParent(); |
| 12294 | |
| 12295 | QualType MPTy = Context.getMemberPointerType( |
| 12296 | op->getType(), |
| 12297 | Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); |
| 12298 | // Under the MS ABI, lock down the inheritance model now. |
| 12299 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
| 12300 | (void)isCompleteType(OpLoc, MPTy); |
| 12301 | return MPTy; |
| 12302 | } |
| 12303 | } |
| 12304 | } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && |
| 12305 | !isa<BindingDecl>(dcl)) |
| 12306 | llvm_unreachable("Unknown/unexpected decl type" ); |
| 12307 | } |
| 12308 | |
| 12309 | if (AddressOfError != AO_No_Error) { |
| 12310 | diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); |
| 12311 | return QualType(); |
| 12312 | } |
| 12313 | |
| 12314 | if (lval == Expr::LV_IncompleteVoidType) { |
| 12315 | // Taking the address of a void variable is technically illegal, but we |
| 12316 | // allow it in cases which are otherwise valid. |
| 12317 | // Example: "extern void x; void* y = &x;". |
| 12318 | Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); |
| 12319 | } |
| 12320 | |
| 12321 | // If the operand has type "type", the result has type "pointer to type". |
| 12322 | if (op->getType()->isObjCObjectType()) |
| 12323 | return Context.getObjCObjectPointerType(op->getType()); |
| 12324 | |
| 12325 | CheckAddressOfPackedMember(op); |
| 12326 | |
| 12327 | ASTContext::PointerInterpretationKind PIK = |
| 12328 | pointerKindForBaseExpr(Context, op); |
| 12329 | return Context.getPointerType(op->getType(), PIK); |
| 12330 | } |
| 12331 | |
| 12332 | static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { |
| 12333 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); |
| 12334 | if (!DRE) |
| 12335 | return; |
| 12336 | const Decl *D = DRE->getDecl(); |
| 12337 | if (!D) |
| 12338 | return; |
| 12339 | const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); |
| 12340 | if (!Param) |
| 12341 | return; |
| 12342 | if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) |
| 12343 | if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) |
| 12344 | return; |
| 12345 | if (FunctionScopeInfo *FD = S.getCurFunction()) |
| 12346 | if (!FD->ModifiedNonNullParams.count(Param)) |
| 12347 | FD->ModifiedNonNullParams.insert(Param); |
| 12348 | } |
| 12349 | |
| 12350 | /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). |
| 12351 | static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, |
| 12352 | SourceLocation OpLoc) { |
| 12353 | if (Op->isTypeDependent()) |
| 12354 | return S.Context.DependentTy; |
| 12355 | |
| 12356 | ExprResult ConvResult = S.UsualUnaryConversions(Op); |
| 12357 | if (ConvResult.isInvalid()) |
| 12358 | return QualType(); |
| 12359 | Op = ConvResult.get(); |
| 12360 | QualType OpTy = Op->getType(); |
| 12361 | QualType Result; |
| 12362 | |
| 12363 | if (isa<CXXReinterpretCastExpr>(Op)) { |
| 12364 | QualType OpOrigType = Op->IgnoreParenCasts()->getType(); |
| 12365 | S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, |
| 12366 | Op->getSourceRange()); |
| 12367 | } |
| 12368 | |
| 12369 | if (const PointerType *PT = OpTy->getAs<PointerType>()) |
| 12370 | { |
| 12371 | Result = PT->getPointeeType(); |
| 12372 | } |
| 12373 | else if (const ObjCObjectPointerType *OPT = |
| 12374 | OpTy->getAs<ObjCObjectPointerType>()) |
| 12375 | Result = OPT->getPointeeType(); |
| 12376 | else { |
| 12377 | ExprResult PR = S.CheckPlaceholderExpr(Op); |
| 12378 | if (PR.isInvalid()) return QualType(); |
| 12379 | if (PR.get() != Op) |
| 12380 | return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); |
| 12381 | } |
| 12382 | |
| 12383 | if (Result.isNull()) { |
| 12384 | S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) |
| 12385 | << OpTy << Op->getSourceRange(); |
| 12386 | return QualType(); |
| 12387 | } |
| 12388 | |
| 12389 | // Note that per both C89 and C99, indirection is always legal, even if Result |
| 12390 | // is an incomplete type or void. It would be possible to warn about |
| 12391 | // dereferencing a void pointer, but it's completely well-defined, and such a |
| 12392 | // warning is unlikely to catch any mistakes. In C++, indirection is not valid |
| 12393 | // for pointers to 'void' but is fine for any other pointer type: |
| 12394 | // |
| 12395 | // C++ [expr.unary.op]p1: |
| 12396 | // [...] the expression to which [the unary * operator] is applied shall |
| 12397 | // be a pointer to an object type, or a pointer to a function type |
| 12398 | if (S.getLangOpts().CPlusPlus && Result->isVoidType()) |
| 12399 | S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) |
| 12400 | << OpTy << Op->getSourceRange(); |
| 12401 | |
| 12402 | // Dereferences are usually l-values... |
| 12403 | VK = VK_LValue; |
| 12404 | |
| 12405 | // ...except that certain expressions are never l-values in C. |
| 12406 | if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) |
| 12407 | VK = VK_RValue; |
| 12408 | |
| 12409 | return Result; |
| 12410 | } |
| 12411 | |
| 12412 | BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { |
| 12413 | BinaryOperatorKind Opc; |
| 12414 | switch (Kind) { |
| 12415 | default: llvm_unreachable("Unknown binop!" ); |
| 12416 | case tok::periodstar: Opc = BO_PtrMemD; break; |
| 12417 | case tok::arrowstar: Opc = BO_PtrMemI; break; |
| 12418 | case tok::star: Opc = BO_Mul; break; |
| 12419 | case tok::slash: Opc = BO_Div; break; |
| 12420 | case tok::percent: Opc = BO_Rem; break; |
| 12421 | case tok::plus: Opc = BO_Add; break; |
| 12422 | case tok::minus: Opc = BO_Sub; break; |
| 12423 | case tok::lessless: Opc = BO_Shl; break; |
| 12424 | case tok::greatergreater: Opc = BO_Shr; break; |
| 12425 | case tok::lessequal: Opc = BO_LE; break; |
| 12426 | case tok::less: Opc = BO_LT; break; |
| 12427 | case tok::greaterequal: Opc = BO_GE; break; |
| 12428 | case tok::greater: Opc = BO_GT; break; |
| 12429 | case tok::exclaimequal: Opc = BO_NE; break; |
| 12430 | case tok::equalequal: Opc = BO_EQ; break; |
| 12431 | case tok::spaceship: Opc = BO_Cmp; break; |
| 12432 | case tok::amp: Opc = BO_And; break; |
| 12433 | case tok::caret: Opc = BO_Xor; break; |
| 12434 | case tok::pipe: Opc = BO_Or; break; |
| 12435 | case tok::ampamp: Opc = BO_LAnd; break; |
| 12436 | case tok::pipepipe: Opc = BO_LOr; break; |
| 12437 | case tok::equal: Opc = BO_Assign; break; |
| 12438 | case tok::starequal: Opc = BO_MulAssign; break; |
| 12439 | case tok::slashequal: Opc = BO_DivAssign; break; |
| 12440 | case tok::percentequal: Opc = BO_RemAssign; break; |
| 12441 | case tok::plusequal: Opc = BO_AddAssign; break; |
| 12442 | case tok::minusequal: Opc = BO_SubAssign; break; |
| 12443 | case tok::lesslessequal: Opc = BO_ShlAssign; break; |
| 12444 | case tok::greatergreaterequal: Opc = BO_ShrAssign; break; |
| 12445 | case tok::ampequal: Opc = BO_AndAssign; break; |
| 12446 | case tok::caretequal: Opc = BO_XorAssign; break; |
| 12447 | case tok::pipeequal: Opc = BO_OrAssign; break; |
| 12448 | case tok::comma: Opc = BO_Comma; break; |
| 12449 | } |
| 12450 | return Opc; |
| 12451 | } |
| 12452 | |
| 12453 | static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( |
| 12454 | tok::TokenKind Kind) { |
| 12455 | UnaryOperatorKind Opc; |
| 12456 | switch (Kind) { |
| 12457 | default: llvm_unreachable("Unknown unary op!" ); |
| 12458 | case tok::plusplus: Opc = UO_PreInc; break; |
| 12459 | case tok::minusminus: Opc = UO_PreDec; break; |
| 12460 | case tok::amp: Opc = UO_AddrOf; break; |
| 12461 | case tok::star: Opc = UO_Deref; break; |
| 12462 | case tok::plus: Opc = UO_Plus; break; |
| 12463 | case tok::minus: Opc = UO_Minus; break; |
| 12464 | case tok::tilde: Opc = UO_Not; break; |
| 12465 | case tok::exclaim: Opc = UO_LNot; break; |
| 12466 | case tok::kw___real: Opc = UO_Real; break; |
| 12467 | case tok::kw___imag: Opc = UO_Imag; break; |
| 12468 | case tok::kw___extension__: Opc = UO_Extension; break; |
| 12469 | } |
| 12470 | return Opc; |
| 12471 | } |
| 12472 | |
| 12473 | /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. |
| 12474 | /// This warning suppressed in the event of macro expansions. |
| 12475 | static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, |
| 12476 | SourceLocation OpLoc, bool IsBuiltin) { |
| 12477 | if (S.inTemplateInstantiation()) |
| 12478 | return; |
| 12479 | if (S.isUnevaluatedContext()) |
| 12480 | return; |
| 12481 | if (OpLoc.isInvalid() || OpLoc.isMacroID()) |
| 12482 | return; |
| 12483 | LHSExpr = LHSExpr->IgnoreParenImpCasts(); |
| 12484 | RHSExpr = RHSExpr->IgnoreParenImpCasts(); |
| 12485 | const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); |
| 12486 | const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); |
| 12487 | if (!LHSDeclRef || !RHSDeclRef || |
| 12488 | LHSDeclRef->getLocation().isMacroID() || |
| 12489 | RHSDeclRef->getLocation().isMacroID()) |
| 12490 | return; |
| 12491 | const ValueDecl *LHSDecl = |
| 12492 | cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); |
| 12493 | const ValueDecl *RHSDecl = |
| 12494 | cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); |
| 12495 | if (LHSDecl != RHSDecl) |
| 12496 | return; |
| 12497 | if (LHSDecl->getType().isVolatileQualified()) |
| 12498 | return; |
| 12499 | if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) |
| 12500 | if (RefTy->getPointeeType().isVolatileQualified()) |
| 12501 | return; |
| 12502 | |
| 12503 | S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin |
| 12504 | : diag::warn_self_assignment_overloaded) |
| 12505 | << LHSDeclRef->getType() << LHSExpr->getSourceRange() |
| 12506 | << RHSExpr->getSourceRange(); |
| 12507 | } |
| 12508 | |
| 12509 | /// Check if a bitwise-& is performed on an Objective-C pointer. This |
| 12510 | /// is usually indicative of introspection within the Objective-C pointer. |
| 12511 | static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, |
| 12512 | SourceLocation OpLoc) { |
| 12513 | if (!S.getLangOpts().ObjC) |
| 12514 | return; |
| 12515 | |
| 12516 | const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; |
| 12517 | const Expr *LHS = L.get(); |
| 12518 | const Expr *RHS = R.get(); |
| 12519 | |
| 12520 | if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
| 12521 | ObjCPointerExpr = LHS; |
| 12522 | OtherExpr = RHS; |
| 12523 | } |
| 12524 | else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { |
| 12525 | ObjCPointerExpr = RHS; |
| 12526 | OtherExpr = LHS; |
| 12527 | } |
| 12528 | |
| 12529 | // This warning is deliberately made very specific to reduce false |
| 12530 | // positives with logic that uses '&' for hashing. This logic mainly |
| 12531 | // looks for code trying to introspect into tagged pointers, which |
| 12532 | // code should generally never do. |
| 12533 | if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { |
| 12534 | unsigned Diag = diag::warn_objc_pointer_masking; |
| 12535 | // Determine if we are introspecting the result of performSelectorXXX. |
| 12536 | const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); |
| 12537 | // Special case messages to -performSelector and friends, which |
| 12538 | // can return non-pointer values boxed in a pointer value. |
| 12539 | // Some clients may wish to silence warnings in this subcase. |
| 12540 | if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { |
| 12541 | Selector S = ME->getSelector(); |
| 12542 | StringRef SelArg0 = S.getNameForSlot(0); |
| 12543 | if (SelArg0.startswith("performSelector" )) |
| 12544 | Diag = diag::warn_objc_pointer_masking_performSelector; |
| 12545 | } |
| 12546 | |
| 12547 | S.Diag(OpLoc, Diag) |
| 12548 | << ObjCPointerExpr->getSourceRange(); |
| 12549 | } |
| 12550 | } |
| 12551 | |
| 12552 | static NamedDecl *getDeclFromExpr(Expr *E) { |
| 12553 | if (!E) |
| 12554 | return nullptr; |
| 12555 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) |
| 12556 | return DRE->getDecl(); |
| 12557 | if (auto *ME = dyn_cast<MemberExpr>(E)) |
| 12558 | return ME->getMemberDecl(); |
| 12559 | if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) |
| 12560 | return IRE->getDecl(); |
| 12561 | return nullptr; |
| 12562 | } |
| 12563 | |
| 12564 | // This helper function promotes a binary operator's operands (which are of a |
| 12565 | // half vector type) to a vector of floats and then truncates the result to |
| 12566 | // a vector of either half or short. |
| 12567 | static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, |
| 12568 | BinaryOperatorKind Opc, QualType ResultTy, |
| 12569 | ExprValueKind VK, ExprObjectKind OK, |
| 12570 | bool IsCompAssign, SourceLocation OpLoc, |
| 12571 | FPOptions FPFeatures) { |
| 12572 | auto &Context = S.getASTContext(); |
| 12573 | assert((isVector(ResultTy, Context.HalfTy) || |
| 12574 | isVector(ResultTy, Context.ShortTy)) && |
| 12575 | "Result must be a vector of half or short" ); |
| 12576 | assert(isVector(LHS.get()->getType(), Context.HalfTy) && |
| 12577 | isVector(RHS.get()->getType(), Context.HalfTy) && |
| 12578 | "both operands expected to be a half vector" ); |
| 12579 | |
| 12580 | RHS = convertVector(RHS.get(), Context.FloatTy, S); |
| 12581 | QualType BinOpResTy = RHS.get()->getType(); |
| 12582 | |
| 12583 | // If Opc is a comparison, ResultType is a vector of shorts. In that case, |
| 12584 | // change BinOpResTy to a vector of ints. |
| 12585 | if (isVector(ResultTy, Context.ShortTy)) |
| 12586 | BinOpResTy = S.GetSignedVectorType(BinOpResTy); |
| 12587 | |
| 12588 | if (IsCompAssign) |
| 12589 | return new (Context) CompoundAssignOperator( |
| 12590 | LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, |
| 12591 | OpLoc, FPFeatures); |
| 12592 | |
| 12593 | LHS = convertVector(LHS.get(), Context.FloatTy, S); |
| 12594 | auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, |
| 12595 | VK, OK, OpLoc, FPFeatures); |
| 12596 | return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); |
| 12597 | } |
| 12598 | |
| 12599 | static std::pair<ExprResult, ExprResult> |
| 12600 | CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, |
| 12601 | Expr *RHSExpr) { |
| 12602 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
| 12603 | if (!S.getLangOpts().CPlusPlus) { |
| 12604 | // C cannot handle TypoExpr nodes on either side of a binop because it |
| 12605 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
| 12606 | // been dealt with before checking the operands. |
| 12607 | LHS = S.CorrectDelayedTyposInExpr(LHS); |
| 12608 | RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { |
| 12609 | if (Opc != BO_Assign) |
| 12610 | return ExprResult(E); |
| 12611 | // Avoid correcting the RHS to the same Expr as the LHS. |
| 12612 | Decl *D = getDeclFromExpr(E); |
| 12613 | return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; |
| 12614 | }); |
| 12615 | } |
| 12616 | return std::make_pair(LHS, RHS); |
| 12617 | } |
| 12618 | |
| 12619 | /// Returns true if conversion between vectors of halfs and vectors of floats |
| 12620 | /// is needed. |
| 12621 | static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, |
| 12622 | QualType SrcType) { |
| 12623 | return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && |
| 12624 | !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && |
| 12625 | isVector(SrcType, Ctx.HalfTy); |
| 12626 | } |
| 12627 | |
| 12628 | /// CreateBuiltinBinOp - Creates a new built-in binary operation with |
| 12629 | /// operator @p Opc at location @c TokLoc. This routine only supports |
| 12630 | /// built-in operations; ActOnBinOp handles overloaded operators. |
| 12631 | ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, |
| 12632 | BinaryOperatorKind Opc, |
| 12633 | Expr *LHSExpr, Expr *RHSExpr) { |
| 12634 | if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { |
| 12635 | // The syntax only allows initializer lists on the RHS of assignment, |
| 12636 | // so we don't need to worry about accepting invalid code for |
| 12637 | // non-assignment operators. |
| 12638 | // C++11 5.17p9: |
| 12639 | // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning |
| 12640 | // of x = {} is x = T(). |
| 12641 | InitializationKind Kind = InitializationKind::CreateDirectList( |
| 12642 | RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 12643 | InitializedEntity Entity = |
| 12644 | InitializedEntity::InitializeTemporary(LHSExpr->getType()); |
| 12645 | InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); |
| 12646 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); |
| 12647 | if (Init.isInvalid()) |
| 12648 | return Init; |
| 12649 | RHSExpr = Init.get(); |
| 12650 | } |
| 12651 | |
| 12652 | ExprResult LHS = LHSExpr, RHS = RHSExpr; |
| 12653 | QualType ResultTy; // Result type of the binary operator. |
| 12654 | // The following two variables are used for compound assignment operators |
| 12655 | QualType CompLHSTy; // Type of LHS after promotions for computation |
| 12656 | QualType CompResultTy; // Type of computation result |
| 12657 | ExprValueKind VK = VK_RValue; |
| 12658 | ExprObjectKind OK = OK_Ordinary; |
| 12659 | bool ConvertHalfVec = false; |
| 12660 | |
| 12661 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); |
| 12662 | if (!LHS.isUsable() || !RHS.isUsable()) |
| 12663 | return ExprError(); |
| 12664 | |
| 12665 | if (getLangOpts().OpenCL) { |
| 12666 | QualType LHSTy = LHSExpr->getType(); |
| 12667 | QualType RHSTy = RHSExpr->getType(); |
| 12668 | // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by |
| 12669 | // the ATOMIC_VAR_INIT macro. |
| 12670 | if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { |
| 12671 | SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); |
| 12672 | if (BO_Assign == Opc) |
| 12673 | Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; |
| 12674 | else |
| 12675 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); |
| 12676 | return ExprError(); |
| 12677 | } |
| 12678 | |
| 12679 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
| 12680 | // only with a builtin functions and therefore should be disallowed here. |
| 12681 | if (LHSTy->isImageType() || RHSTy->isImageType() || |
| 12682 | LHSTy->isSamplerT() || RHSTy->isSamplerT() || |
| 12683 | LHSTy->isPipeType() || RHSTy->isPipeType() || |
| 12684 | LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { |
| 12685 | ResultTy = InvalidOperands(OpLoc, LHS, RHS); |
| 12686 | return ExprError(); |
| 12687 | } |
| 12688 | } |
| 12689 | |
| 12690 | // Diagnose operations on the unsupported types for OpenMP device compilation. |
| 12691 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { |
| 12692 | if (Opc != BO_Assign && Opc != BO_Comma) { |
| 12693 | checkOpenMPDeviceExpr(LHSExpr); |
| 12694 | checkOpenMPDeviceExpr(RHSExpr); |
| 12695 | } |
| 12696 | } |
| 12697 | |
| 12698 | switch (Opc) { |
| 12699 | case BO_Assign: |
| 12700 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); |
| 12701 | if (getLangOpts().CPlusPlus && |
| 12702 | LHS.get()->getObjectKind() != OK_ObjCProperty) { |
| 12703 | VK = LHS.get()->getValueKind(); |
| 12704 | OK = LHS.get()->getObjectKind(); |
| 12705 | } |
| 12706 | if (!ResultTy.isNull()) { |
| 12707 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); |
| 12708 | DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); |
| 12709 | |
| 12710 | // Avoid copying a block to the heap if the block is assigned to a local |
| 12711 | // auto variable that is declared in the same scope as the block. This |
| 12712 | // optimization is unsafe if the local variable is declared in an outer |
| 12713 | // scope. For example: |
| 12714 | // |
| 12715 | // BlockTy b; |
| 12716 | // { |
| 12717 | // b = ^{...}; |
| 12718 | // } |
| 12719 | // // It is unsafe to invoke the block here if it wasn't copied to the |
| 12720 | // // heap. |
| 12721 | // b(); |
| 12722 | |
| 12723 | if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) |
| 12724 | if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) |
| 12725 | if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) |
| 12726 | if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) |
| 12727 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); |
| 12728 | } |
| 12729 | RecordModifiableNonNullParam(*this, LHS.get()); |
| 12730 | break; |
| 12731 | case BO_PtrMemD: |
| 12732 | case BO_PtrMemI: |
| 12733 | ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, |
| 12734 | Opc == BO_PtrMemI); |
| 12735 | break; |
| 12736 | case BO_Mul: |
| 12737 | case BO_Div: |
| 12738 | ConvertHalfVec = true; |
| 12739 | ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, |
| 12740 | Opc == BO_Div); |
| 12741 | break; |
| 12742 | case BO_Rem: |
| 12743 | ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); |
| 12744 | break; |
| 12745 | case BO_Add: |
| 12746 | ConvertHalfVec = true; |
| 12747 | ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); |
| 12748 | break; |
| 12749 | case BO_Sub: |
| 12750 | ConvertHalfVec = true; |
| 12751 | ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); |
| 12752 | break; |
| 12753 | case BO_Shl: |
| 12754 | case BO_Shr: |
| 12755 | ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); |
| 12756 | break; |
| 12757 | case BO_LE: |
| 12758 | case BO_LT: |
| 12759 | case BO_GE: |
| 12760 | case BO_GT: |
| 12761 | ConvertHalfVec = true; |
| 12762 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); |
| 12763 | break; |
| 12764 | case BO_EQ: |
| 12765 | case BO_NE: |
| 12766 | ConvertHalfVec = true; |
| 12767 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); |
| 12768 | break; |
| 12769 | case BO_Cmp: |
| 12770 | ConvertHalfVec = true; |
| 12771 | ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); |
| 12772 | assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); |
| 12773 | break; |
| 12774 | case BO_And: |
| 12775 | checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); |
| 12776 | LLVM_FALLTHROUGH; |
| 12777 | case BO_Xor: |
| 12778 | case BO_Or: |
| 12779 | ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); |
| 12780 | break; |
| 12781 | case BO_LAnd: |
| 12782 | case BO_LOr: |
| 12783 | ConvertHalfVec = true; |
| 12784 | ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); |
| 12785 | break; |
| 12786 | case BO_MulAssign: |
| 12787 | case BO_DivAssign: |
| 12788 | ConvertHalfVec = true; |
| 12789 | CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, |
| 12790 | Opc == BO_DivAssign); |
| 12791 | CompLHSTy = CompResultTy; |
| 12792 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 12793 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); |
| 12794 | break; |
| 12795 | case BO_RemAssign: |
| 12796 | CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); |
| 12797 | CompLHSTy = CompResultTy; |
| 12798 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 12799 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); |
| 12800 | break; |
| 12801 | case BO_AddAssign: |
| 12802 | ConvertHalfVec = true; |
| 12803 | CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); |
| 12804 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 12805 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); |
| 12806 | break; |
| 12807 | case BO_SubAssign: |
| 12808 | ConvertHalfVec = true; |
| 12809 | CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); |
| 12810 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 12811 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); |
| 12812 | break; |
| 12813 | case BO_ShlAssign: |
| 12814 | case BO_ShrAssign: |
| 12815 | CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); |
| 12816 | CompLHSTy = CompResultTy; |
| 12817 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 12818 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); |
| 12819 | break; |
| 12820 | case BO_AndAssign: |
| 12821 | case BO_OrAssign: // fallthrough |
| 12822 | DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); |
| 12823 | LLVM_FALLTHROUGH; |
| 12824 | case BO_XorAssign: |
| 12825 | CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); |
| 12826 | CompLHSTy = CompResultTy; |
| 12827 | if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) |
| 12828 | ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); |
| 12829 | break; |
| 12830 | case BO_Comma: |
| 12831 | ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); |
| 12832 | if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { |
| 12833 | VK = RHS.get()->getValueKind(); |
| 12834 | OK = RHS.get()->getObjectKind(); |
| 12835 | } |
| 12836 | break; |
| 12837 | } |
| 12838 | if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) |
| 12839 | return ExprError(); |
| 12840 | |
| 12841 | // Some of the binary operations require promoting operands of half vector to |
| 12842 | // float vectors and truncating the result back to half vector. For now, we do |
| 12843 | // this only when HalfArgsAndReturn is set (that is, when the target is arm or |
| 12844 | // arm64). |
| 12845 | assert(isVector(RHS.get()->getType(), Context.HalfTy) == |
| 12846 | isVector(LHS.get()->getType(), Context.HalfTy) && |
| 12847 | "both sides are half vectors or neither sides are" ); |
| 12848 | ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, |
| 12849 | LHS.get()->getType()); |
| 12850 | |
| 12851 | // Check for array bounds violations for both sides of the BinaryOperator |
| 12852 | CheckArrayAccess(LHS.get()); |
| 12853 | CheckArrayAccess(RHS.get()); |
| 12854 | |
| 12855 | if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { |
| 12856 | NamedDecl *ObjectSetClass = LookupSingleName(TUScope, |
| 12857 | &Context.Idents.get("object_setClass" ), |
| 12858 | SourceLocation(), LookupOrdinaryName); |
| 12859 | if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { |
| 12860 | SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); |
| 12861 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) |
| 12862 | << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), |
| 12863 | "object_setClass(" ) |
| 12864 | << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), |
| 12865 | "," ) |
| 12866 | << FixItHint::CreateInsertion(RHSLocEnd, ")" ); |
| 12867 | } |
| 12868 | else |
| 12869 | Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); |
| 12870 | } |
| 12871 | else if (const ObjCIvarRefExpr *OIRE = |
| 12872 | dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) |
| 12873 | DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); |
| 12874 | |
| 12875 | // Opc is not a compound assignment if CompResultTy is null. |
| 12876 | if (CompResultTy.isNull()) { |
| 12877 | if (ConvertHalfVec) |
| 12878 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, |
| 12879 | OpLoc, FPFeatures); |
| 12880 | return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, |
| 12881 | OK, OpLoc, FPFeatures); |
| 12882 | } |
| 12883 | |
| 12884 | // Handle compound assignments. |
| 12885 | if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != |
| 12886 | OK_ObjCProperty) { |
| 12887 | VK = VK_LValue; |
| 12888 | OK = LHS.get()->getObjectKind(); |
| 12889 | } |
| 12890 | |
| 12891 | if (ConvertHalfVec) |
| 12892 | return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, |
| 12893 | OpLoc, FPFeatures); |
| 12894 | |
| 12895 | return new (Context) CompoundAssignOperator( |
| 12896 | LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, |
| 12897 | OpLoc, FPFeatures); |
| 12898 | } |
| 12899 | |
| 12900 | /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison |
| 12901 | /// operators are mixed in a way that suggests that the programmer forgot that |
| 12902 | /// comparison operators have higher precedence. The most typical example of |
| 12903 | /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". |
| 12904 | static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, |
| 12905 | SourceLocation OpLoc, Expr *LHSExpr, |
| 12906 | Expr *RHSExpr) { |
| 12907 | BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); |
| 12908 | BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); |
| 12909 | |
| 12910 | // Check that one of the sides is a comparison operator and the other isn't. |
| 12911 | bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); |
| 12912 | bool isRightComp = RHSBO && RHSBO->isComparisonOp(); |
| 12913 | if (isLeftComp == isRightComp) |
| 12914 | return; |
| 12915 | |
| 12916 | // Bitwise operations are sometimes used as eager logical ops. |
| 12917 | // Don't diagnose this. |
| 12918 | bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); |
| 12919 | bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); |
| 12920 | if (isLeftBitwise || isRightBitwise) |
| 12921 | return; |
| 12922 | |
| 12923 | SourceRange DiagRange = isLeftComp |
| 12924 | ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) |
| 12925 | : SourceRange(OpLoc, RHSExpr->getEndLoc()); |
| 12926 | StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); |
| 12927 | SourceRange ParensRange = |
| 12928 | isLeftComp |
| 12929 | ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) |
| 12930 | : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); |
| 12931 | |
| 12932 | Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) |
| 12933 | << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; |
| 12934 | SuggestParentheses(Self, OpLoc, |
| 12935 | Self.PDiag(diag::note_precedence_silence) << OpStr, |
| 12936 | (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); |
| 12937 | SuggestParentheses(Self, OpLoc, |
| 12938 | Self.PDiag(diag::note_precedence_bitwise_first) |
| 12939 | << BinaryOperator::getOpcodeStr(Opc), |
| 12940 | ParensRange); |
| 12941 | } |
| 12942 | |
| 12943 | /// It accepts a '&&' expr that is inside a '||' one. |
| 12944 | /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression |
| 12945 | /// in parentheses. |
| 12946 | static void |
| 12947 | EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, |
| 12948 | BinaryOperator *Bop) { |
| 12949 | assert(Bop->getOpcode() == BO_LAnd); |
| 12950 | Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) |
| 12951 | << Bop->getSourceRange() << OpLoc; |
| 12952 | SuggestParentheses(Self, Bop->getOperatorLoc(), |
| 12953 | Self.PDiag(diag::note_precedence_silence) |
| 12954 | << Bop->getOpcodeStr(), |
| 12955 | Bop->getSourceRange()); |
| 12956 | } |
| 12957 | |
| 12958 | /// Returns true if the given expression can be evaluated as a constant |
| 12959 | /// 'true'. |
| 12960 | static bool EvaluatesAsTrue(Sema &S, Expr *E) { |
| 12961 | bool Res; |
| 12962 | return !E->isValueDependent() && |
| 12963 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; |
| 12964 | } |
| 12965 | |
| 12966 | /// Returns true if the given expression can be evaluated as a constant |
| 12967 | /// 'false'. |
| 12968 | static bool EvaluatesAsFalse(Sema &S, Expr *E) { |
| 12969 | bool Res; |
| 12970 | return !E->isValueDependent() && |
| 12971 | E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; |
| 12972 | } |
| 12973 | |
| 12974 | /// Look for '&&' in the left hand of a '||' expr. |
| 12975 | static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, |
| 12976 | Expr *LHSExpr, Expr *RHSExpr) { |
| 12977 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { |
| 12978 | if (Bop->getOpcode() == BO_LAnd) { |
| 12979 | // If it's "a && b || 0" don't warn since the precedence doesn't matter. |
| 12980 | if (EvaluatesAsFalse(S, RHSExpr)) |
| 12981 | return; |
| 12982 | // If it's "1 && a || b" don't warn since the precedence doesn't matter. |
| 12983 | if (!EvaluatesAsTrue(S, Bop->getLHS())) |
| 12984 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); |
| 12985 | } else if (Bop->getOpcode() == BO_LOr) { |
| 12986 | if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { |
| 12987 | // If it's "a || b && 1 || c" we didn't warn earlier for |
| 12988 | // "a || b && 1", but warn now. |
| 12989 | if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) |
| 12990 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); |
| 12991 | } |
| 12992 | } |
| 12993 | } |
| 12994 | } |
| 12995 | |
| 12996 | /// Look for '&&' in the right hand of a '||' expr. |
| 12997 | static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, |
| 12998 | Expr *LHSExpr, Expr *RHSExpr) { |
| 12999 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { |
| 13000 | if (Bop->getOpcode() == BO_LAnd) { |
| 13001 | // If it's "0 || a && b" don't warn since the precedence doesn't matter. |
| 13002 | if (EvaluatesAsFalse(S, LHSExpr)) |
| 13003 | return; |
| 13004 | // If it's "a || b && 1" don't warn since the precedence doesn't matter. |
| 13005 | if (!EvaluatesAsTrue(S, Bop->getRHS())) |
| 13006 | return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); |
| 13007 | } |
| 13008 | } |
| 13009 | } |
| 13010 | |
| 13011 | /// Look for bitwise op in the left or right hand of a bitwise op with |
| 13012 | /// lower precedence and emit a diagnostic together with a fixit hint that wraps |
| 13013 | /// the '&' expression in parentheses. |
| 13014 | static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, |
| 13015 | SourceLocation OpLoc, Expr *SubExpr) { |
| 13016 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { |
| 13017 | if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { |
| 13018 | S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) |
| 13019 | << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) |
| 13020 | << Bop->getSourceRange() << OpLoc; |
| 13021 | SuggestParentheses(S, Bop->getOperatorLoc(), |
| 13022 | S.PDiag(diag::note_precedence_silence) |
| 13023 | << Bop->getOpcodeStr(), |
| 13024 | Bop->getSourceRange()); |
| 13025 | } |
| 13026 | } |
| 13027 | } |
| 13028 | |
| 13029 | static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, |
| 13030 | Expr *SubExpr, StringRef Shift) { |
| 13031 | if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { |
| 13032 | if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { |
| 13033 | StringRef Op = Bop->getOpcodeStr(); |
| 13034 | S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) |
| 13035 | << Bop->getSourceRange() << OpLoc << Shift << Op; |
| 13036 | SuggestParentheses(S, Bop->getOperatorLoc(), |
| 13037 | S.PDiag(diag::note_precedence_silence) << Op, |
| 13038 | Bop->getSourceRange()); |
| 13039 | } |
| 13040 | } |
| 13041 | } |
| 13042 | |
| 13043 | static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, |
| 13044 | Expr *LHSExpr, Expr *RHSExpr) { |
| 13045 | CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); |
| 13046 | if (!OCE) |
| 13047 | return; |
| 13048 | |
| 13049 | FunctionDecl *FD = OCE->getDirectCallee(); |
| 13050 | if (!FD || !FD->isOverloadedOperator()) |
| 13051 | return; |
| 13052 | |
| 13053 | OverloadedOperatorKind Kind = FD->getOverloadedOperator(); |
| 13054 | if (Kind != OO_LessLess && Kind != OO_GreaterGreater) |
| 13055 | return; |
| 13056 | |
| 13057 | S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) |
| 13058 | << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() |
| 13059 | << (Kind == OO_LessLess); |
| 13060 | SuggestParentheses(S, OCE->getOperatorLoc(), |
| 13061 | S.PDiag(diag::note_precedence_silence) |
| 13062 | << (Kind == OO_LessLess ? "<<" : ">>" ), |
| 13063 | OCE->getSourceRange()); |
| 13064 | SuggestParentheses( |
| 13065 | S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), |
| 13066 | SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); |
| 13067 | } |
| 13068 | |
| 13069 | /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky |
| 13070 | /// precedence. |
| 13071 | static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, |
| 13072 | SourceLocation OpLoc, Expr *LHSExpr, |
| 13073 | Expr *RHSExpr){ |
| 13074 | // Diagnose "arg1 'bitwise' arg2 'eq' arg3". |
| 13075 | if (BinaryOperator::isBitwiseOp(Opc)) |
| 13076 | DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); |
| 13077 | |
| 13078 | // Diagnose "arg1 & arg2 | arg3" |
| 13079 | if ((Opc == BO_Or || Opc == BO_Xor) && |
| 13080 | !OpLoc.isMacroID()/* Don't warn in macros. */) { |
| 13081 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); |
| 13082 | DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); |
| 13083 | } |
| 13084 | |
| 13085 | // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. |
| 13086 | // We don't warn for 'assert(a || b && "bad")' since this is safe. |
| 13087 | if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { |
| 13088 | DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); |
| 13089 | DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); |
| 13090 | } |
| 13091 | |
| 13092 | if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) |
| 13093 | || Opc == BO_Shr) { |
| 13094 | StringRef Shift = BinaryOperator::getOpcodeStr(Opc); |
| 13095 | DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); |
| 13096 | DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); |
| 13097 | } |
| 13098 | |
| 13099 | // Warn on overloaded shift operators and comparisons, such as: |
| 13100 | // cout << 5 == 4; |
| 13101 | if (BinaryOperator::isComparisonOp(Opc)) |
| 13102 | DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); |
| 13103 | } |
| 13104 | |
| 13105 | // Binary Operators. 'Tok' is the token for the operator. |
| 13106 | ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, |
| 13107 | tok::TokenKind Kind, |
| 13108 | Expr *LHSExpr, Expr *RHSExpr) { |
| 13109 | BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); |
| 13110 | assert(LHSExpr && "ActOnBinOp(): missing left expression" ); |
| 13111 | assert(RHSExpr && "ActOnBinOp(): missing right expression" ); |
| 13112 | |
| 13113 | // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" |
| 13114 | DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); |
| 13115 | |
| 13116 | return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); |
| 13117 | } |
| 13118 | |
| 13119 | /// Build an overloaded binary operator expression in the given scope. |
| 13120 | static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, |
| 13121 | BinaryOperatorKind Opc, |
| 13122 | Expr *LHS, Expr *RHS) { |
| 13123 | switch (Opc) { |
| 13124 | case BO_Assign: |
| 13125 | case BO_DivAssign: |
| 13126 | case BO_RemAssign: |
| 13127 | case BO_SubAssign: |
| 13128 | case BO_AndAssign: |
| 13129 | case BO_OrAssign: |
| 13130 | case BO_XorAssign: |
| 13131 | DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); |
| 13132 | CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); |
| 13133 | break; |
| 13134 | default: |
| 13135 | break; |
| 13136 | } |
| 13137 | |
| 13138 | // Find all of the overloaded operators visible from this |
| 13139 | // point. We perform both an operator-name lookup from the local |
| 13140 | // scope and an argument-dependent lookup based on the types of |
| 13141 | // the arguments. |
| 13142 | UnresolvedSet<16> Functions; |
| 13143 | OverloadedOperatorKind OverOp |
| 13144 | = BinaryOperator::getOverloadedOperator(Opc); |
| 13145 | if (Sc && OverOp != OO_None && OverOp != OO_Equal) |
| 13146 | S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), |
| 13147 | RHS->getType(), Functions); |
| 13148 | |
| 13149 | // Build the (potentially-overloaded, potentially-dependent) |
| 13150 | // binary operation. |
| 13151 | return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); |
| 13152 | } |
| 13153 | |
| 13154 | ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, |
| 13155 | BinaryOperatorKind Opc, |
| 13156 | Expr *LHSExpr, Expr *RHSExpr) { |
| 13157 | ExprResult LHS, RHS; |
| 13158 | std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); |
| 13159 | if (!LHS.isUsable() || !RHS.isUsable()) |
| 13160 | return ExprError(); |
| 13161 | LHSExpr = LHS.get(); |
| 13162 | RHSExpr = RHS.get(); |
| 13163 | |
| 13164 | // We want to end up calling one of checkPseudoObjectAssignment |
| 13165 | // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if |
| 13166 | // both expressions are overloadable or either is type-dependent), |
| 13167 | // or CreateBuiltinBinOp (in any other case). We also want to get |
| 13168 | // any placeholder types out of the way. |
| 13169 | |
| 13170 | // Handle pseudo-objects in the LHS. |
| 13171 | if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { |
| 13172 | // Assignments with a pseudo-object l-value need special analysis. |
| 13173 | if (pty->getKind() == BuiltinType::PseudoObject && |
| 13174 | BinaryOperator::isAssignmentOp(Opc)) |
| 13175 | return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); |
| 13176 | |
| 13177 | // Don't resolve overloads if the other type is overloadable. |
| 13178 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { |
| 13179 | // We can't actually test that if we still have a placeholder, |
| 13180 | // though. Fortunately, none of the exceptions we see in that |
| 13181 | // code below are valid when the LHS is an overload set. Note |
| 13182 | // that an overload set can be dependently-typed, but it never |
| 13183 | // instantiates to having an overloadable type. |
| 13184 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); |
| 13185 | if (resolvedRHS.isInvalid()) return ExprError(); |
| 13186 | RHSExpr = resolvedRHS.get(); |
| 13187 | |
| 13188 | if (RHSExpr->isTypeDependent() || |
| 13189 | RHSExpr->getType()->isOverloadableType()) |
| 13190 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); |
| 13191 | } |
| 13192 | |
| 13193 | // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function |
| 13194 | // template, diagnose the missing 'template' keyword instead of diagnosing |
| 13195 | // an invalid use of a bound member function. |
| 13196 | // |
| 13197 | // Note that "A::x < b" might be valid if 'b' has an overloadable type due |
| 13198 | // to C++1z [over.over]/1.4, but we already checked for that case above. |
| 13199 | if (Opc == BO_LT && inTemplateInstantiation() && |
| 13200 | (pty->getKind() == BuiltinType::BoundMember || |
| 13201 | pty->getKind() == BuiltinType::Overload)) { |
| 13202 | auto *OE = dyn_cast<OverloadExpr>(LHSExpr); |
| 13203 | if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && |
| 13204 | std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { |
| 13205 | return isa<FunctionTemplateDecl>(ND); |
| 13206 | })) { |
| 13207 | Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() |
| 13208 | : OE->getNameLoc(), |
| 13209 | diag::err_template_kw_missing) |
| 13210 | << OE->getName().getAsString() << "" ; |
| 13211 | return ExprError(); |
| 13212 | } |
| 13213 | } |
| 13214 | |
| 13215 | ExprResult LHS = CheckPlaceholderExpr(LHSExpr); |
| 13216 | if (LHS.isInvalid()) return ExprError(); |
| 13217 | LHSExpr = LHS.get(); |
| 13218 | } |
| 13219 | |
| 13220 | // Handle pseudo-objects in the RHS. |
| 13221 | if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { |
| 13222 | // An overload in the RHS can potentially be resolved by the type |
| 13223 | // being assigned to. |
| 13224 | if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { |
| 13225 | if (getLangOpts().CPlusPlus && |
| 13226 | (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || |
| 13227 | LHSExpr->getType()->isOverloadableType())) |
| 13228 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); |
| 13229 | |
| 13230 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); |
| 13231 | } |
| 13232 | |
| 13233 | // Don't resolve overloads if the other type is overloadable. |
| 13234 | if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && |
| 13235 | LHSExpr->getType()->isOverloadableType()) |
| 13236 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); |
| 13237 | |
| 13238 | ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); |
| 13239 | if (!resolvedRHS.isUsable()) return ExprError(); |
| 13240 | RHSExpr = resolvedRHS.get(); |
| 13241 | } |
| 13242 | |
| 13243 | if (getLangOpts().CPlusPlus) { |
| 13244 | // If either expression is type-dependent, always build an |
| 13245 | // overloaded op. |
| 13246 | if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) |
| 13247 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); |
| 13248 | |
| 13249 | // Otherwise, build an overloaded op if either expression has an |
| 13250 | // overloadable type. |
| 13251 | if (LHSExpr->getType()->isOverloadableType() || |
| 13252 | RHSExpr->getType()->isOverloadableType()) |
| 13253 | return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); |
| 13254 | } |
| 13255 | |
| 13256 | // Build a built-in binary operation. |
| 13257 | return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); |
| 13258 | } |
| 13259 | |
| 13260 | static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { |
| 13261 | if (T.isNull() || T->isDependentType()) |
| 13262 | return false; |
| 13263 | |
| 13264 | if (!T->isPromotableIntegerType()) |
| 13265 | return true; |
| 13266 | |
| 13267 | return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); |
| 13268 | } |
| 13269 | |
| 13270 | ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, |
| 13271 | UnaryOperatorKind Opc, |
| 13272 | Expr *InputExpr) { |
| 13273 | if (InputExpr->getType().getQualifiers().hasOutput()) { |
| 13274 | return ExprError(Diag(InputExpr->getExprLoc(), diag::err_typecheck_read_output) |
| 13275 | << InputExpr->getSourceRange()); |
| 13276 | } |
| 13277 | |
| 13278 | |
| 13279 | ExprResult Input = InputExpr; |
| 13280 | ExprValueKind VK = VK_RValue; |
| 13281 | ExprObjectKind OK = OK_Ordinary; |
| 13282 | QualType resultType; |
| 13283 | bool CanOverflow = false; |
| 13284 | |
| 13285 | bool ConvertHalfVec = false; |
| 13286 | if (getLangOpts().OpenCL) { |
| 13287 | QualType Ty = InputExpr->getType(); |
| 13288 | // The only legal unary operation for atomics is '&'. |
| 13289 | if ((Opc != UO_AddrOf && Ty->isAtomicType()) || |
| 13290 | // OpenCL special types - image, sampler, pipe, and blocks are to be used |
| 13291 | // only with a builtin functions and therefore should be disallowed here. |
| 13292 | (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() |
| 13293 | || Ty->isBlockPointerType())) { |
| 13294 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13295 | << InputExpr->getType() |
| 13296 | << Input.get()->getSourceRange()); |
| 13297 | } |
| 13298 | } |
| 13299 | // Diagnose operations on the unsupported types for OpenMP device compilation. |
| 13300 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { |
| 13301 | if (UnaryOperator::isIncrementDecrementOp(Opc) || |
| 13302 | UnaryOperator::isArithmeticOp(Opc)) |
| 13303 | checkOpenMPDeviceExpr(InputExpr); |
| 13304 | } |
| 13305 | |
| 13306 | switch (Opc) { |
| 13307 | case UO_PreInc: |
| 13308 | case UO_PreDec: |
| 13309 | case UO_PostInc: |
| 13310 | case UO_PostDec: |
| 13311 | resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, |
| 13312 | OpLoc, |
| 13313 | Opc == UO_PreInc || |
| 13314 | Opc == UO_PostInc, |
| 13315 | Opc == UO_PreInc || |
| 13316 | Opc == UO_PreDec); |
| 13317 | CanOverflow = isOverflowingIntegerType(Context, resultType); |
| 13318 | break; |
| 13319 | case UO_AddrOf: |
| 13320 | resultType = CheckAddressOfOperand(Input, OpLoc); |
| 13321 | CheckAddressOfNoDeref(InputExpr); |
| 13322 | RecordModifiableNonNullParam(*this, InputExpr); |
| 13323 | break; |
| 13324 | case UO_Deref: { |
| 13325 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); |
| 13326 | if (Input.isInvalid()) return ExprError(); |
| 13327 | resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); |
| 13328 | break; |
| 13329 | } |
| 13330 | case UO_Plus: |
| 13331 | case UO_Minus: |
| 13332 | CanOverflow = Opc == UO_Minus && |
| 13333 | isOverflowingIntegerType(Context, Input.get()->getType()); |
| 13334 | Input = UsualUnaryConversions(Input.get()); |
| 13335 | if (Input.isInvalid()) return ExprError(); |
| 13336 | // Unary plus and minus require promoting an operand of half vector to a |
| 13337 | // float vector and truncating the result back to a half vector. For now, we |
| 13338 | // do this only when HalfArgsAndReturns is set (that is, when the target is |
| 13339 | // arm or arm64). |
| 13340 | ConvertHalfVec = |
| 13341 | needsConversionOfHalfVec(true, Context, Input.get()->getType()); |
| 13342 | |
| 13343 | // If the operand is a half vector, promote it to a float vector. |
| 13344 | if (ConvertHalfVec) |
| 13345 | Input = convertVector(Input.get(), Context.FloatTy, *this); |
| 13346 | resultType = Input.get()->getType(); |
| 13347 | if (resultType->isDependentType()) |
| 13348 | break; |
| 13349 | if (resultType->isArithmeticType()) // C99 6.5.3.3p1 |
| 13350 | break; |
| 13351 | else if (resultType->isVectorType() && |
| 13352 | // The z vector extensions don't allow + or - with bool vectors. |
| 13353 | (!Context.getLangOpts().ZVector || |
| 13354 | resultType->getAs<VectorType>()->getVectorKind() != |
| 13355 | VectorType::AltiVecBool)) |
| 13356 | break; |
| 13357 | else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 |
| 13358 | Opc == UO_Plus && |
| 13359 | resultType->isPointerType()) |
| 13360 | break; |
| 13361 | |
| 13362 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13363 | << resultType << Input.get()->getSourceRange()); |
| 13364 | |
| 13365 | case UO_Not: // bitwise complement |
| 13366 | Input = UsualUnaryConversions(Input.get()); |
| 13367 | if (Input.isInvalid()) |
| 13368 | return ExprError(); |
| 13369 | resultType = Input.get()->getType(); |
| 13370 | |
| 13371 | if (resultType->isDependentType()) |
| 13372 | break; |
| 13373 | // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. |
| 13374 | if (resultType->isComplexType() || resultType->isComplexIntegerType()) |
| 13375 | // C99 does not support '~' for complex conjugation. |
| 13376 | Diag(OpLoc, diag::ext_integer_complement_complex) |
| 13377 | << resultType << Input.get()->getSourceRange(); |
| 13378 | else if (resultType->hasIntegerRepresentation()) |
| 13379 | break; |
| 13380 | else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { |
| 13381 | // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate |
| 13382 | // on vector float types. |
| 13383 | QualType T = resultType->getAs<ExtVectorType>()->getElementType(); |
| 13384 | if (!T->isIntegerType()) |
| 13385 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13386 | << resultType << Input.get()->getSourceRange()); |
| 13387 | } else { |
| 13388 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13389 | << resultType << Input.get()->getSourceRange()); |
| 13390 | } |
| 13391 | break; |
| 13392 | |
| 13393 | case UO_LNot: // logical negation |
| 13394 | // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). |
| 13395 | Input = DefaultFunctionArrayLvalueConversion(Input.get()); |
| 13396 | if (Input.isInvalid()) return ExprError(); |
| 13397 | resultType = Input.get()->getType(); |
| 13398 | |
| 13399 | // Though we still have to promote half FP to float... |
| 13400 | if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { |
| 13401 | Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); |
| 13402 | resultType = Context.FloatTy; |
| 13403 | } |
| 13404 | |
| 13405 | if (resultType->isDependentType()) |
| 13406 | break; |
| 13407 | if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { |
| 13408 | // C99 6.5.3.3p1: ok, fallthrough; |
| 13409 | if (Context.getLangOpts().CPlusPlus) { |
| 13410 | // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: |
| 13411 | // operand contextually converted to bool. |
| 13412 | Input = ImpCastExprToType(Input.get(), Context.BoolTy, |
| 13413 | ScalarTypeToBooleanCastKind(resultType)); |
| 13414 | } else if (Context.getLangOpts().OpenCL && |
| 13415 | Context.getLangOpts().OpenCLVersion < 120) { |
| 13416 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
| 13417 | // operate on scalar float types. |
| 13418 | if (!resultType->isIntegerType() && !resultType->isPointerType()) |
| 13419 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13420 | << resultType << Input.get()->getSourceRange()); |
| 13421 | } |
| 13422 | } else if (resultType->isExtVectorType()) { |
| 13423 | if (Context.getLangOpts().OpenCL && |
| 13424 | Context.getLangOpts().OpenCLVersion < 120 && |
| 13425 | !Context.getLangOpts().OpenCLCPlusPlus) { |
| 13426 | // OpenCL v1.1 6.3.h: The logical operator not (!) does not |
| 13427 | // operate on vector float types. |
| 13428 | QualType T = resultType->getAs<ExtVectorType>()->getElementType(); |
| 13429 | if (!T->isIntegerType()) |
| 13430 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13431 | << resultType << Input.get()->getSourceRange()); |
| 13432 | } |
| 13433 | // Vector logical not returns the signed variant of the operand type. |
| 13434 | resultType = GetSignedVectorType(resultType); |
| 13435 | break; |
| 13436 | } else { |
| 13437 | // FIXME: GCC's vector extension permits the usage of '!' with a vector |
| 13438 | // type in C++. We should allow that here too. |
| 13439 | return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) |
| 13440 | << resultType << Input.get()->getSourceRange()); |
| 13441 | } |
| 13442 | |
| 13443 | // LNot always has type int. C99 6.5.3.3p5. |
| 13444 | // In C++, it's bool. C++ 5.3.1p8 |
| 13445 | resultType = Context.getLogicalOperationType(); |
| 13446 | break; |
| 13447 | case UO_Real: |
| 13448 | case UO_Imag: |
| 13449 | resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); |
| 13450 | // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary |
| 13451 | // complex l-values to ordinary l-values and all other values to r-values. |
| 13452 | if (Input.isInvalid()) return ExprError(); |
| 13453 | if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { |
| 13454 | if (Input.get()->getValueKind() != VK_RValue && |
| 13455 | Input.get()->getObjectKind() == OK_Ordinary) |
| 13456 | VK = Input.get()->getValueKind(); |
| 13457 | } else if (!getLangOpts().CPlusPlus) { |
| 13458 | // In C, a volatile scalar is read by __imag. In C++, it is not. |
| 13459 | Input = DefaultLvalueConversion(Input.get()); |
| 13460 | } |
| 13461 | break; |
| 13462 | case UO_Extension: |
| 13463 | resultType = Input.get()->getType(); |
| 13464 | VK = Input.get()->getValueKind(); |
| 13465 | OK = Input.get()->getObjectKind(); |
| 13466 | break; |
| 13467 | case UO_Coawait: |
| 13468 | // It's unnecessary to represent the pass-through operator co_await in the |
| 13469 | // AST; just return the input expression instead. |
| 13470 | assert(!Input.get()->getType()->isDependentType() && |
| 13471 | "the co_await expression must be non-dependant before " |
| 13472 | "building operator co_await" ); |
| 13473 | return Input; |
| 13474 | } |
| 13475 | if (resultType.isNull() || Input.isInvalid()) |
| 13476 | return ExprError(); |
| 13477 | |
| 13478 | // Check for array bounds violations in the operand of the UnaryOperator, |
| 13479 | // except for the '*' and '&' operators that have to be handled specially |
| 13480 | // by CheckArrayAccess (as there are special cases like &array[arraysize] |
| 13481 | // that are explicitly defined as valid by the standard). |
| 13482 | if (Opc != UO_AddrOf && Opc != UO_Deref) |
| 13483 | CheckArrayAccess(Input.get()); |
| 13484 | |
| 13485 | auto *UO = new (Context) |
| 13486 | UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); |
| 13487 | |
| 13488 | if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && |
| 13489 | !isa<ArrayType>(UO->getType().getDesugaredType(Context))) |
| 13490 | ExprEvalContexts.back().PossibleDerefs.insert(UO); |
| 13491 | |
| 13492 | // Convert the result back to a half vector. |
| 13493 | if (ConvertHalfVec) |
| 13494 | return convertVector(UO, Context.HalfTy, *this); |
| 13495 | return UO; |
| 13496 | } |
| 13497 | |
| 13498 | /// Determine whether the given expression is a qualified member |
| 13499 | /// access expression, of a form that could be turned into a pointer to member |
| 13500 | /// with the address-of operator. |
| 13501 | bool Sema::isQualifiedMemberAccess(Expr *E) { |
| 13502 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { |
| 13503 | if (!DRE->getQualifier()) |
| 13504 | return false; |
| 13505 | |
| 13506 | ValueDecl *VD = DRE->getDecl(); |
| 13507 | if (!VD->isCXXClassMember()) |
| 13508 | return false; |
| 13509 | |
| 13510 | if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) |
| 13511 | return true; |
| 13512 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) |
| 13513 | return Method->isInstance(); |
| 13514 | |
| 13515 | return false; |
| 13516 | } |
| 13517 | |
| 13518 | if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { |
| 13519 | if (!ULE->getQualifier()) |
| 13520 | return false; |
| 13521 | |
| 13522 | for (NamedDecl *D : ULE->decls()) { |
| 13523 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { |
| 13524 | if (Method->isInstance()) |
| 13525 | return true; |
| 13526 | } else { |
| 13527 | // Overload set does not contain methods. |
| 13528 | break; |
| 13529 | } |
| 13530 | } |
| 13531 | |
| 13532 | return false; |
| 13533 | } |
| 13534 | |
| 13535 | return false; |
| 13536 | } |
| 13537 | |
| 13538 | ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, |
| 13539 | UnaryOperatorKind Opc, Expr *Input) { |
| 13540 | // First things first: handle placeholders so that the |
| 13541 | // overloaded-operator check considers the right type. |
| 13542 | if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { |
| 13543 | // Increment and decrement of pseudo-object references. |
| 13544 | if (pty->getKind() == BuiltinType::PseudoObject && |
| 13545 | UnaryOperator::isIncrementDecrementOp(Opc)) |
| 13546 | return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); |
| 13547 | |
| 13548 | // extension is always a builtin operator. |
| 13549 | if (Opc == UO_Extension) |
| 13550 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); |
| 13551 | |
| 13552 | // & gets special logic for several kinds of placeholder. |
| 13553 | // The builtin code knows what to do. |
| 13554 | if (Opc == UO_AddrOf && |
| 13555 | (pty->getKind() == BuiltinType::Overload || |
| 13556 | pty->getKind() == BuiltinType::UnknownAny || |
| 13557 | pty->getKind() == BuiltinType::BoundMember)) |
| 13558 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); |
| 13559 | |
| 13560 | // Anything else needs to be handled now. |
| 13561 | ExprResult Result = CheckPlaceholderExpr(Input); |
| 13562 | if (Result.isInvalid()) return ExprError(); |
| 13563 | Input = Result.get(); |
| 13564 | } |
| 13565 | |
| 13566 | if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && |
| 13567 | UnaryOperator::getOverloadedOperator(Opc) != OO_None && |
| 13568 | !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { |
| 13569 | // Find all of the overloaded operators visible from this |
| 13570 | // point. We perform both an operator-name lookup from the local |
| 13571 | // scope and an argument-dependent lookup based on the types of |
| 13572 | // the arguments. |
| 13573 | UnresolvedSet<16> Functions; |
| 13574 | OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); |
| 13575 | if (S && OverOp != OO_None) |
| 13576 | LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), |
| 13577 | Functions); |
| 13578 | |
| 13579 | return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); |
| 13580 | } |
| 13581 | |
| 13582 | return CreateBuiltinUnaryOp(OpLoc, Opc, Input); |
| 13583 | } |
| 13584 | |
| 13585 | // Unary Operators. 'Tok' is the token for the operator. |
| 13586 | ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, |
| 13587 | tok::TokenKind Op, Expr *Input) { |
| 13588 | return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); |
| 13589 | } |
| 13590 | |
| 13591 | /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". |
| 13592 | ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, |
| 13593 | LabelDecl *TheDecl) { |
| 13594 | TheDecl->markUsed(Context); |
| 13595 | // Create the AST node. The address of a label always has type 'void*'. |
| 13596 | return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, |
| 13597 | Context.getPointerType(Context.VoidTy)); |
| 13598 | } |
| 13599 | |
| 13600 | void Sema::ActOnStartStmtExpr() { |
| 13601 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); |
| 13602 | } |
| 13603 | |
| 13604 | void Sema::ActOnStmtExprError() { |
| 13605 | // Note that function is also called by TreeTransform when leaving a |
| 13606 | // StmtExpr scope without rebuilding anything. |
| 13607 | |
| 13608 | DiscardCleanupsInEvaluationContext(); |
| 13609 | PopExpressionEvaluationContext(); |
| 13610 | } |
| 13611 | |
| 13612 | ExprResult |
| 13613 | Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, |
| 13614 | SourceLocation RPLoc) { // "({..})" |
| 13615 | assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!" ); |
| 13616 | CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); |
| 13617 | |
| 13618 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
| 13619 | DiscardCleanupsInEvaluationContext(); |
| 13620 | assert(!Cleanup.exprNeedsCleanups() && |
| 13621 | "cleanups within StmtExpr not correctly bound!" ); |
| 13622 | PopExpressionEvaluationContext(); |
| 13623 | |
| 13624 | // FIXME: there are a variety of strange constraints to enforce here, for |
| 13625 | // example, it is not possible to goto into a stmt expression apparently. |
| 13626 | // More semantic analysis is needed. |
| 13627 | |
| 13628 | // If there are sub-stmts in the compound stmt, take the type of the last one |
| 13629 | // as the type of the stmtexpr. |
| 13630 | QualType Ty = Context.VoidTy; |
| 13631 | bool StmtExprMayBindToTemp = false; |
| 13632 | if (!Compound->body_empty()) { |
| 13633 | if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) { |
| 13634 | if (const Expr *Value = LastStmt->getExprStmt()) { |
| 13635 | StmtExprMayBindToTemp = true; |
| 13636 | Ty = Value->getType(); |
| 13637 | } |
| 13638 | } |
| 13639 | } |
| 13640 | |
| 13641 | // FIXME: Check that expression type is complete/non-abstract; statement |
| 13642 | // expressions are not lvalues. |
| 13643 | Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); |
| 13644 | if (StmtExprMayBindToTemp) |
| 13645 | return MaybeBindToTemporary(ResStmtExpr); |
| 13646 | return ResStmtExpr; |
| 13647 | } |
| 13648 | |
| 13649 | ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { |
| 13650 | if (ER.isInvalid()) |
| 13651 | return ExprError(); |
| 13652 | |
| 13653 | // Do function/array conversion on the last expression, but not |
| 13654 | // lvalue-to-rvalue. However, initialize an unqualified type. |
| 13655 | ER = DefaultFunctionArrayConversion(ER.get()); |
| 13656 | if (ER.isInvalid()) |
| 13657 | return ExprError(); |
| 13658 | Expr *E = ER.get(); |
| 13659 | |
| 13660 | if (E->isTypeDependent()) |
| 13661 | return E; |
| 13662 | |
| 13663 | // In ARC, if the final expression ends in a consume, splice |
| 13664 | // the consume out and bind it later. In the alternate case |
| 13665 | // (when dealing with a retainable type), the result |
| 13666 | // initialization will create a produce. In both cases the |
| 13667 | // result will be +1, and we'll need to balance that out with |
| 13668 | // a bind. |
| 13669 | auto *Cast = dyn_cast<ImplicitCastExpr>(E); |
| 13670 | if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) |
| 13671 | return Cast->getSubExpr(); |
| 13672 | |
| 13673 | // FIXME: Provide a better location for the initialization. |
| 13674 | return PerformCopyInitialization( |
| 13675 | InitializedEntity::InitializeStmtExprResult( |
| 13676 | E->getBeginLoc(), E->getType().getUnqualifiedType()), |
| 13677 | SourceLocation(), E); |
| 13678 | } |
| 13679 | |
| 13680 | ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, |
| 13681 | TypeSourceInfo *TInfo, |
| 13682 | ArrayRef<OffsetOfComponent> Components, |
| 13683 | SourceLocation RParenLoc) { |
| 13684 | QualType ArgTy = TInfo->getType(); |
| 13685 | bool Dependent = ArgTy->isDependentType(); |
| 13686 | SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); |
| 13687 | |
| 13688 | // We must have at least one component that refers to the type, and the first |
| 13689 | // one is known to be a field designator. Verify that the ArgTy represents |
| 13690 | // a struct/union/class. |
| 13691 | if (!Dependent && !ArgTy->isRecordType()) |
| 13692 | return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) |
| 13693 | << ArgTy << TypeRange); |
| 13694 | |
| 13695 | // Type must be complete per C99 7.17p3 because a declaring a variable |
| 13696 | // with an incomplete type would be ill-formed. |
| 13697 | if (!Dependent |
| 13698 | && RequireCompleteType(BuiltinLoc, ArgTy, |
| 13699 | diag::err_offsetof_incomplete_type, TypeRange)) |
| 13700 | return ExprError(); |
| 13701 | |
| 13702 | bool DidWarnAboutNonPOD = false; |
| 13703 | QualType CurrentType = ArgTy; |
| 13704 | SmallVector<OffsetOfNode, 4> Comps; |
| 13705 | SmallVector<Expr*, 4> Exprs; |
| 13706 | for (const OffsetOfComponent &OC : Components) { |
| 13707 | if (OC.isBrackets) { |
| 13708 | // Offset of an array sub-field. TODO: Should we allow vector elements? |
| 13709 | if (!CurrentType->isDependentType()) { |
| 13710 | const ArrayType *AT = Context.getAsArrayType(CurrentType); |
| 13711 | if(!AT) |
| 13712 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) |
| 13713 | << CurrentType); |
| 13714 | CurrentType = AT->getElementType(); |
| 13715 | } else |
| 13716 | CurrentType = Context.DependentTy; |
| 13717 | |
| 13718 | ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); |
| 13719 | if (IdxRval.isInvalid()) |
| 13720 | return ExprError(); |
| 13721 | Expr *Idx = IdxRval.get(); |
| 13722 | |
| 13723 | // The expression must be an integral expression. |
| 13724 | // FIXME: An integral constant expression? |
| 13725 | if (!Idx->isTypeDependent() && !Idx->isValueDependent() && |
| 13726 | !Idx->getType()->isIntegerType()) |
| 13727 | return ExprError( |
| 13728 | Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) |
| 13729 | << Idx->getSourceRange()); |
| 13730 | |
| 13731 | // Record this array index. |
| 13732 | Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); |
| 13733 | Exprs.push_back(Idx); |
| 13734 | continue; |
| 13735 | } |
| 13736 | |
| 13737 | // Offset of a field. |
| 13738 | if (CurrentType->isDependentType()) { |
| 13739 | // We have the offset of a field, but we can't look into the dependent |
| 13740 | // type. Just record the identifier of the field. |
| 13741 | Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); |
| 13742 | CurrentType = Context.DependentTy; |
| 13743 | continue; |
| 13744 | } |
| 13745 | |
| 13746 | // We need to have a complete type to look into. |
| 13747 | if (RequireCompleteType(OC.LocStart, CurrentType, |
| 13748 | diag::err_offsetof_incomplete_type)) |
| 13749 | return ExprError(); |
| 13750 | |
| 13751 | // Look for the designated field. |
| 13752 | const RecordType *RC = CurrentType->getAs<RecordType>(); |
| 13753 | if (!RC) |
| 13754 | return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) |
| 13755 | << CurrentType); |
| 13756 | RecordDecl *RD = RC->getDecl(); |
| 13757 | |
| 13758 | // C++ [lib.support.types]p5: |
| 13759 | // The macro offsetof accepts a restricted set of type arguments in this |
| 13760 | // International Standard. type shall be a POD structure or a POD union |
| 13761 | // (clause 9). |
| 13762 | // C++11 [support.types]p4: |
| 13763 | // If type is not a standard-layout class (Clause 9), the results are |
| 13764 | // undefined. |
| 13765 | if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { |
| 13766 | bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); |
| 13767 | unsigned DiagID = |
| 13768 | LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type |
| 13769 | : diag::ext_offsetof_non_pod_type; |
| 13770 | |
| 13771 | if (!IsSafe && !DidWarnAboutNonPOD && |
| 13772 | DiagRuntimeBehavior(BuiltinLoc, nullptr, |
| 13773 | PDiag(DiagID) |
| 13774 | << SourceRange(Components[0].LocStart, OC.LocEnd) |
| 13775 | << CurrentType)) |
| 13776 | DidWarnAboutNonPOD = true; |
| 13777 | } |
| 13778 | |
| 13779 | // Look for the field. |
| 13780 | LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); |
| 13781 | LookupQualifiedName(R, RD); |
| 13782 | FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); |
| 13783 | IndirectFieldDecl *IndirectMemberDecl = nullptr; |
| 13784 | if (!MemberDecl) { |
| 13785 | if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) |
| 13786 | MemberDecl = IndirectMemberDecl->getAnonField(); |
| 13787 | } |
| 13788 | |
| 13789 | if (!MemberDecl) |
| 13790 | return ExprError(Diag(BuiltinLoc, diag::err_no_member) |
| 13791 | << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, |
| 13792 | OC.LocEnd)); |
| 13793 | |
| 13794 | // C99 7.17p3: |
| 13795 | // (If the specified member is a bit-field, the behavior is undefined.) |
| 13796 | // |
| 13797 | // We diagnose this as an error. |
| 13798 | if (MemberDecl->isBitField()) { |
| 13799 | Diag(OC.LocEnd, diag::err_offsetof_bitfield) |
| 13800 | << MemberDecl->getDeclName() |
| 13801 | << SourceRange(BuiltinLoc, RParenLoc); |
| 13802 | Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); |
| 13803 | return ExprError(); |
| 13804 | } |
| 13805 | |
| 13806 | RecordDecl *Parent = MemberDecl->getParent(); |
| 13807 | if (IndirectMemberDecl) |
| 13808 | Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); |
| 13809 | |
| 13810 | // If the member was found in a base class, introduce OffsetOfNodes for |
| 13811 | // the base class indirections. |
| 13812 | CXXBasePaths Paths; |
| 13813 | if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), |
| 13814 | Paths)) { |
| 13815 | if (Paths.getDetectedVirtual()) { |
| 13816 | Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) |
| 13817 | << MemberDecl->getDeclName() |
| 13818 | << SourceRange(BuiltinLoc, RParenLoc); |
| 13819 | return ExprError(); |
| 13820 | } |
| 13821 | |
| 13822 | CXXBasePath &Path = Paths.front(); |
| 13823 | for (const CXXBasePathElement &B : Path) |
| 13824 | Comps.push_back(OffsetOfNode(B.Base)); |
| 13825 | } |
| 13826 | |
| 13827 | if (IndirectMemberDecl) { |
| 13828 | for (auto *FI : IndirectMemberDecl->chain()) { |
| 13829 | assert(isa<FieldDecl>(FI)); |
| 13830 | Comps.push_back(OffsetOfNode(OC.LocStart, |
| 13831 | cast<FieldDecl>(FI), OC.LocEnd)); |
| 13832 | } |
| 13833 | } else |
| 13834 | Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); |
| 13835 | |
| 13836 | CurrentType = MemberDecl->getType().getNonReferenceType(); |
| 13837 | } |
| 13838 | |
| 13839 | return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, |
| 13840 | Comps, Exprs, RParenLoc); |
| 13841 | } |
| 13842 | |
| 13843 | ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, |
| 13844 | SourceLocation BuiltinLoc, |
| 13845 | SourceLocation TypeLoc, |
| 13846 | ParsedType ParsedArgTy, |
| 13847 | ArrayRef<OffsetOfComponent> Components, |
| 13848 | SourceLocation RParenLoc) { |
| 13849 | |
| 13850 | TypeSourceInfo *ArgTInfo; |
| 13851 | QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); |
| 13852 | if (ArgTy.isNull()) |
| 13853 | return ExprError(); |
| 13854 | |
| 13855 | if (!ArgTInfo) |
| 13856 | ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); |
| 13857 | |
| 13858 | return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); |
| 13859 | } |
| 13860 | |
| 13861 | |
| 13862 | ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, |
| 13863 | Expr *CondExpr, |
| 13864 | Expr *LHSExpr, Expr *RHSExpr, |
| 13865 | SourceLocation RPLoc) { |
| 13866 | assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)" ); |
| 13867 | |
| 13868 | ExprValueKind VK = VK_RValue; |
| 13869 | ExprObjectKind OK = OK_Ordinary; |
| 13870 | QualType resType; |
| 13871 | bool ValueDependent = false; |
| 13872 | bool CondIsTrue = false; |
| 13873 | if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { |
| 13874 | resType = Context.DependentTy; |
| 13875 | ValueDependent = true; |
| 13876 | } else { |
| 13877 | // The conditional expression is required to be a constant expression. |
| 13878 | llvm::APSInt condEval(32); |
| 13879 | ExprResult CondICE |
| 13880 | = VerifyIntegerConstantExpression(CondExpr, &condEval, |
| 13881 | diag::err_typecheck_choose_expr_requires_constant, false); |
| 13882 | if (CondICE.isInvalid()) |
| 13883 | return ExprError(); |
| 13884 | CondExpr = CondICE.get(); |
| 13885 | CondIsTrue = condEval.getZExtValue(); |
| 13886 | |
| 13887 | // If the condition is > zero, then the AST type is the same as the LHSExpr. |
| 13888 | Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; |
| 13889 | |
| 13890 | resType = ActiveExpr->getType(); |
| 13891 | ValueDependent = ActiveExpr->isValueDependent(); |
| 13892 | VK = ActiveExpr->getValueKind(); |
| 13893 | OK = ActiveExpr->getObjectKind(); |
| 13894 | } |
| 13895 | |
| 13896 | return new (Context) |
| 13897 | ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, |
| 13898 | CondIsTrue, resType->isDependentType(), ValueDependent); |
| 13899 | } |
| 13900 | |
| 13901 | //===----------------------------------------------------------------------===// |
| 13902 | // Clang Extensions. |
| 13903 | //===----------------------------------------------------------------------===// |
| 13904 | |
| 13905 | /// ActOnBlockStart - This callback is invoked when a block literal is started. |
| 13906 | void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { |
| 13907 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); |
| 13908 | |
| 13909 | if (LangOpts.CPlusPlus) { |
| 13910 | Decl *ManglingContextDecl; |
| 13911 | if (MangleNumberingContext *MCtx = |
| 13912 | getCurrentMangleNumberContext(Block->getDeclContext(), |
| 13913 | ManglingContextDecl)) { |
| 13914 | unsigned ManglingNumber = MCtx->getManglingNumber(Block); |
| 13915 | Block->setBlockMangling(ManglingNumber, ManglingContextDecl); |
| 13916 | } |
| 13917 | } |
| 13918 | |
| 13919 | PushBlockScope(CurScope, Block); |
| 13920 | CurContext->addDecl(Block); |
| 13921 | if (CurScope) |
| 13922 | PushDeclContext(CurScope, Block); |
| 13923 | else |
| 13924 | CurContext = Block; |
| 13925 | |
| 13926 | getCurBlock()->HasImplicitReturnType = true; |
| 13927 | |
| 13928 | // Enter a new evaluation context to insulate the block from any |
| 13929 | // cleanups from the enclosing full-expression. |
| 13930 | PushExpressionEvaluationContext( |
| 13931 | ExpressionEvaluationContext::PotentiallyEvaluated); |
| 13932 | } |
| 13933 | |
| 13934 | void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, |
| 13935 | Scope *CurScope) { |
| 13936 | assert(ParamInfo.getIdentifier() == nullptr && |
| 13937 | "block-id should have no identifier!" ); |
| 13938 | assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); |
| 13939 | BlockScopeInfo *CurBlock = getCurBlock(); |
| 13940 | |
| 13941 | TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); |
| 13942 | QualType T = Sig->getType(); |
| 13943 | |
| 13944 | // FIXME: We should allow unexpanded parameter packs here, but that would, |
| 13945 | // in turn, make the block expression contain unexpanded parameter packs. |
| 13946 | if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { |
| 13947 | // Drop the parameters. |
| 13948 | FunctionProtoType::ExtProtoInfo EPI; |
| 13949 | EPI.HasTrailingReturn = false; |
| 13950 | EPI.TypeQuals.addConst(); |
| 13951 | T = Context.getFunctionType(Context.DependentTy, None, EPI); |
| 13952 | Sig = Context.getTrivialTypeSourceInfo(T); |
| 13953 | } |
| 13954 | |
| 13955 | // GetTypeForDeclarator always produces a function type for a block |
| 13956 | // literal signature. Furthermore, it is always a FunctionProtoType |
| 13957 | // unless the function was written with a typedef. |
| 13958 | assert(T->isFunctionType() && |
| 13959 | "GetTypeForDeclarator made a non-function block signature" ); |
| 13960 | |
| 13961 | // Look for an explicit signature in that function type. |
| 13962 | FunctionProtoTypeLoc ExplicitSignature; |
| 13963 | |
| 13964 | if ((ExplicitSignature = Sig->getTypeLoc() |
| 13965 | .getAsAdjusted<FunctionProtoTypeLoc>())) { |
| 13966 | |
| 13967 | // Check whether that explicit signature was synthesized by |
| 13968 | // GetTypeForDeclarator. If so, don't save that as part of the |
| 13969 | // written signature. |
| 13970 | if (ExplicitSignature.getLocalRangeBegin() == |
| 13971 | ExplicitSignature.getLocalRangeEnd()) { |
| 13972 | // This would be much cheaper if we stored TypeLocs instead of |
| 13973 | // TypeSourceInfos. |
| 13974 | TypeLoc Result = ExplicitSignature.getReturnLoc(); |
| 13975 | unsigned Size = Result.getFullDataSize(); |
| 13976 | Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); |
| 13977 | Sig->getTypeLoc().initializeFullCopy(Result, Size); |
| 13978 | |
| 13979 | ExplicitSignature = FunctionProtoTypeLoc(); |
| 13980 | } |
| 13981 | } |
| 13982 | |
| 13983 | CurBlock->TheDecl->setSignatureAsWritten(Sig); |
| 13984 | CurBlock->FunctionType = T; |
| 13985 | |
| 13986 | const FunctionType *Fn = T->getAs<FunctionType>(); |
| 13987 | QualType RetTy = Fn->getReturnType(); |
| 13988 | bool isVariadic = |
| 13989 | (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); |
| 13990 | |
| 13991 | CurBlock->TheDecl->setIsVariadic(isVariadic); |
| 13992 | |
| 13993 | // Context.DependentTy is used as a placeholder for a missing block |
| 13994 | // return type. TODO: what should we do with declarators like: |
| 13995 | // ^ * { ... } |
| 13996 | // If the answer is "apply template argument deduction".... |
| 13997 | if (RetTy != Context.DependentTy) { |
| 13998 | CurBlock->ReturnType = RetTy; |
| 13999 | CurBlock->TheDecl->setBlockMissingReturnType(false); |
| 14000 | CurBlock->HasImplicitReturnType = false; |
| 14001 | } |
| 14002 | |
| 14003 | // Push block parameters from the declarator if we had them. |
| 14004 | SmallVector<ParmVarDecl*, 8> Params; |
| 14005 | if (ExplicitSignature) { |
| 14006 | for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { |
| 14007 | ParmVarDecl *Param = ExplicitSignature.getParam(I); |
| 14008 | if (Param->getIdentifier() == nullptr && |
| 14009 | !Param->isImplicit() && |
| 14010 | !Param->isInvalidDecl() && |
| 14011 | !getLangOpts().CPlusPlus) |
| 14012 | Diag(Param->getLocation(), diag::err_parameter_name_omitted); |
| 14013 | Params.push_back(Param); |
| 14014 | } |
| 14015 | |
| 14016 | // Fake up parameter variables if we have a typedef, like |
| 14017 | // ^ fntype { ... } |
| 14018 | } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { |
| 14019 | for (const auto &I : Fn->param_types()) { |
| 14020 | ParmVarDecl *Param = BuildParmVarDeclForTypedef( |
| 14021 | CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); |
| 14022 | Params.push_back(Param); |
| 14023 | } |
| 14024 | } |
| 14025 | |
| 14026 | // Set the parameters on the block decl. |
| 14027 | if (!Params.empty()) { |
| 14028 | CurBlock->TheDecl->setParams(Params); |
| 14029 | CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), |
| 14030 | /*CheckParameterNames=*/false); |
| 14031 | } |
| 14032 | |
| 14033 | // Finally we can process decl attributes. |
| 14034 | ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); |
| 14035 | |
| 14036 | // Put the parameter variables in scope. |
| 14037 | for (auto AI : CurBlock->TheDecl->parameters()) { |
| 14038 | AI->setOwningFunction(CurBlock->TheDecl); |
| 14039 | |
| 14040 | // If this has an identifier, add it to the scope stack. |
| 14041 | if (AI->getIdentifier()) { |
| 14042 | CheckShadow(CurBlock->TheScope, AI); |
| 14043 | |
| 14044 | PushOnScopeChains(AI, CurBlock->TheScope); |
| 14045 | } |
| 14046 | } |
| 14047 | } |
| 14048 | |
| 14049 | /// ActOnBlockError - If there is an error parsing a block, this callback |
| 14050 | /// is invoked to pop the information about the block from the action impl. |
| 14051 | void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { |
| 14052 | // Leave the expression-evaluation context. |
| 14053 | DiscardCleanupsInEvaluationContext(); |
| 14054 | PopExpressionEvaluationContext(); |
| 14055 | |
| 14056 | // Pop off CurBlock, handle nested blocks. |
| 14057 | PopDeclContext(); |
| 14058 | PopFunctionScopeInfo(); |
| 14059 | } |
| 14060 | |
| 14061 | /// ActOnBlockStmtExpr - This is called when the body of a block statement |
| 14062 | /// literal was successfully completed. ^(int x){...} |
| 14063 | ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, |
| 14064 | Stmt *Body, Scope *CurScope) { |
| 14065 | // If blocks are disabled, emit an error. |
| 14066 | if (!LangOpts.Blocks) |
| 14067 | Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; |
| 14068 | |
| 14069 | // Leave the expression-evaluation context. |
| 14070 | if (hasAnyUnrecoverableErrorsInThisFunction()) |
| 14071 | DiscardCleanupsInEvaluationContext(); |
| 14072 | assert(!Cleanup.exprNeedsCleanups() && |
| 14073 | "cleanups within block not correctly bound!" ); |
| 14074 | PopExpressionEvaluationContext(); |
| 14075 | |
| 14076 | BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); |
| 14077 | BlockDecl *BD = BSI->TheDecl; |
| 14078 | |
| 14079 | if (BSI->HasImplicitReturnType) |
| 14080 | deduceClosureReturnType(*BSI); |
| 14081 | |
| 14082 | QualType RetTy = Context.VoidTy; |
| 14083 | if (!BSI->ReturnType.isNull()) |
| 14084 | RetTy = BSI->ReturnType; |
| 14085 | |
| 14086 | bool NoReturn = BD->hasAttr<NoReturnAttr>(); |
| 14087 | QualType BlockTy; |
| 14088 | |
| 14089 | // If the user wrote a function type in some form, try to use that. |
| 14090 | if (!BSI->FunctionType.isNull()) { |
| 14091 | const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); |
| 14092 | |
| 14093 | FunctionType::ExtInfo Ext = FTy->getExtInfo(); |
| 14094 | if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); |
| 14095 | |
| 14096 | // Turn protoless block types into nullary block types. |
| 14097 | if (isa<FunctionNoProtoType>(FTy)) { |
| 14098 | FunctionProtoType::ExtProtoInfo EPI; |
| 14099 | EPI.ExtInfo = Ext; |
| 14100 | BlockTy = Context.getFunctionType(RetTy, None, EPI); |
| 14101 | |
| 14102 | // Otherwise, if we don't need to change anything about the function type, |
| 14103 | // preserve its sugar structure. |
| 14104 | } else if (FTy->getReturnType() == RetTy && |
| 14105 | (!NoReturn || FTy->getNoReturnAttr())) { |
| 14106 | BlockTy = BSI->FunctionType; |
| 14107 | |
| 14108 | // Otherwise, make the minimal modifications to the function type. |
| 14109 | } else { |
| 14110 | const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); |
| 14111 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
| 14112 | EPI.TypeQuals = Qualifiers(); |
| 14113 | EPI.ExtInfo = Ext; |
| 14114 | BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); |
| 14115 | } |
| 14116 | |
| 14117 | // If we don't have a function type, just build one from nothing. |
| 14118 | } else { |
| 14119 | FunctionProtoType::ExtProtoInfo EPI; |
| 14120 | EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); |
| 14121 | BlockTy = Context.getFunctionType(RetTy, None, EPI); |
| 14122 | } |
| 14123 | |
| 14124 | DiagnoseUnusedParameters(BD->parameters()); |
| 14125 | BlockTy = Context.getBlockPointerType(BlockTy); |
| 14126 | |
| 14127 | // If needed, diagnose invalid gotos and switches in the block. |
| 14128 | if (getCurFunction()->NeedsScopeChecking() && |
| 14129 | !PP.isCodeCompletionEnabled()) |
| 14130 | DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); |
| 14131 | |
| 14132 | BD->setBody(cast<CompoundStmt>(Body)); |
| 14133 | |
| 14134 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) |
| 14135 | DiagnoseUnguardedAvailabilityViolations(BD); |
| 14136 | |
| 14137 | // Try to apply the named return value optimization. We have to check again |
| 14138 | // if we can do this, though, because blocks keep return statements around |
| 14139 | // to deduce an implicit return type. |
| 14140 | if (getLangOpts().CPlusPlus && RetTy->isRecordType() && |
| 14141 | !BD->isDependentContext()) |
| 14142 | computeNRVO(Body, BSI); |
| 14143 | |
| 14144 | PopDeclContext(); |
| 14145 | |
| 14146 | // Pop the block scope now but keep it alive to the end of this function. |
| 14147 | AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); |
| 14148 | PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); |
| 14149 | |
| 14150 | // Set the captured variables on the block. |
| 14151 | SmallVector<BlockDecl::Capture, 4> Captures; |
| 14152 | for (Capture &Cap : BSI->Captures) { |
| 14153 | if (Cap.isInvalid() || Cap.isThisCapture()) |
| 14154 | continue; |
| 14155 | |
| 14156 | VarDecl *Var = Cap.getVariable(); |
| 14157 | Expr *CopyExpr = nullptr; |
| 14158 | if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { |
| 14159 | if (const RecordType *Record = |
| 14160 | Cap.getCaptureType()->getAs<RecordType>()) { |
| 14161 | // The capture logic needs the destructor, so make sure we mark it. |
| 14162 | // Usually this is unnecessary because most local variables have |
| 14163 | // their destructors marked at declaration time, but parameters are |
| 14164 | // an exception because it's technically only the call site that |
| 14165 | // actually requires the destructor. |
| 14166 | if (isa<ParmVarDecl>(Var)) |
| 14167 | FinalizeVarWithDestructor(Var, Record); |
| 14168 | |
| 14169 | // Enter a separate potentially-evaluated context while building block |
| 14170 | // initializers to isolate their cleanups from those of the block |
| 14171 | // itself. |
| 14172 | // FIXME: Is this appropriate even when the block itself occurs in an |
| 14173 | // unevaluated operand? |
| 14174 | EnterExpressionEvaluationContext EvalContext( |
| 14175 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); |
| 14176 | |
| 14177 | SourceLocation Loc = Cap.getLocation(); |
| 14178 | |
| 14179 | ExprResult Result = BuildDeclarationNameExpr( |
| 14180 | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); |
| 14181 | |
| 14182 | // According to the blocks spec, the capture of a variable from |
| 14183 | // the stack requires a const copy constructor. This is not true |
| 14184 | // of the copy/move done to move a __block variable to the heap. |
| 14185 | if (!Result.isInvalid() && |
| 14186 | !Result.get()->getType().isConstQualified()) { |
| 14187 | Result = ImpCastExprToType(Result.get(), |
| 14188 | Result.get()->getType().withConst(), |
| 14189 | CK_NoOp, VK_LValue); |
| 14190 | } |
| 14191 | |
| 14192 | if (!Result.isInvalid()) { |
| 14193 | Result = PerformCopyInitialization( |
| 14194 | InitializedEntity::InitializeBlock(Var->getLocation(), |
| 14195 | Cap.getCaptureType(), false), |
| 14196 | Loc, Result.get()); |
| 14197 | } |
| 14198 | |
| 14199 | // Build a full-expression copy expression if initialization |
| 14200 | // succeeded and used a non-trivial constructor. Recover from |
| 14201 | // errors by pretending that the copy isn't necessary. |
| 14202 | if (!Result.isInvalid() && |
| 14203 | !cast<CXXConstructExpr>(Result.get())->getConstructor() |
| 14204 | ->isTrivial()) { |
| 14205 | Result = MaybeCreateExprWithCleanups(Result); |
| 14206 | CopyExpr = Result.get(); |
| 14207 | } |
| 14208 | } |
| 14209 | } |
| 14210 | |
| 14211 | BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), |
| 14212 | CopyExpr); |
| 14213 | Captures.push_back(NewCap); |
| 14214 | } |
| 14215 | BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); |
| 14216 | |
| 14217 | BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); |
| 14218 | |
| 14219 | // If the block isn't obviously global, i.e. it captures anything at |
| 14220 | // all, then we need to do a few things in the surrounding context: |
| 14221 | if (Result->getBlockDecl()->hasCaptures()) { |
| 14222 | // First, this expression has a new cleanup object. |
| 14223 | ExprCleanupObjects.push_back(Result->getBlockDecl()); |
| 14224 | Cleanup.setExprNeedsCleanups(true); |
| 14225 | |
| 14226 | // It also gets a branch-protected scope if any of the captured |
| 14227 | // variables needs destruction. |
| 14228 | for (const auto &CI : Result->getBlockDecl()->captures()) { |
| 14229 | const VarDecl *var = CI.getVariable(); |
| 14230 | if (var->getType().isDestructedType() != QualType::DK_none) { |
| 14231 | setFunctionHasBranchProtectedScope(); |
| 14232 | break; |
| 14233 | } |
| 14234 | } |
| 14235 | } |
| 14236 | |
| 14237 | if (getCurFunction()) |
| 14238 | getCurFunction()->addBlock(BD); |
| 14239 | |
| 14240 | return Result; |
| 14241 | } |
| 14242 | |
| 14243 | ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, |
| 14244 | SourceLocation RPLoc) { |
| 14245 | TypeSourceInfo *TInfo; |
| 14246 | GetTypeFromParser(Ty, &TInfo); |
| 14247 | return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); |
| 14248 | } |
| 14249 | |
| 14250 | ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, |
| 14251 | Expr *E, TypeSourceInfo *TInfo, |
| 14252 | SourceLocation RPLoc) { |
| 14253 | Expr *OrigExpr = E; |
| 14254 | bool IsMS = false; |
| 14255 | |
| 14256 | // CUDA device code does not support varargs. |
| 14257 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { |
| 14258 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { |
| 14259 | CUDAFunctionTarget T = IdentifyCUDATarget(F); |
| 14260 | if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) |
| 14261 | return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); |
| 14262 | } |
| 14263 | } |
| 14264 | |
| 14265 | // NVPTX does not support va_arg expression. |
| 14266 | if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && |
| 14267 | Context.getTargetInfo().getTriple().isNVPTX()) |
| 14268 | targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); |
| 14269 | |
| 14270 | // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() |
| 14271 | // as Microsoft ABI on an actual Microsoft platform, where |
| 14272 | // __builtin_ms_va_list and __builtin_va_list are the same.) |
| 14273 | if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && |
| 14274 | Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { |
| 14275 | QualType MSVaListType = Context.getBuiltinMSVaListType(); |
| 14276 | if (Context.hasSameType(MSVaListType, E->getType())) { |
| 14277 | if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) |
| 14278 | return ExprError(); |
| 14279 | IsMS = true; |
| 14280 | } |
| 14281 | } |
| 14282 | |
| 14283 | // Get the va_list type |
| 14284 | QualType VaListType = Context.getBuiltinVaListType(); |
| 14285 | if (!IsMS) { |
| 14286 | if (VaListType->isArrayType()) { |
| 14287 | // Deal with implicit array decay; for example, on x86-64, |
| 14288 | // va_list is an array, but it's supposed to decay to |
| 14289 | // a pointer for va_arg. |
| 14290 | VaListType = Context.getArrayDecayedType(VaListType); |
| 14291 | // Make sure the input expression also decays appropriately. |
| 14292 | ExprResult Result = UsualUnaryConversions(E); |
| 14293 | if (Result.isInvalid()) |
| 14294 | return ExprError(); |
| 14295 | E = Result.get(); |
| 14296 | } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { |
| 14297 | // If va_list is a record type and we are compiling in C++ mode, |
| 14298 | // check the argument using reference binding. |
| 14299 | InitializedEntity Entity = InitializedEntity::InitializeParameter( |
| 14300 | Context, Context.getLValueReferenceType(VaListType), false); |
| 14301 | ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); |
| 14302 | if (Init.isInvalid()) |
| 14303 | return ExprError(); |
| 14304 | E = Init.getAs<Expr>(); |
| 14305 | } else { |
| 14306 | // Otherwise, the va_list argument must be an l-value because |
| 14307 | // it is modified by va_arg. |
| 14308 | if (!E->isTypeDependent() && |
| 14309 | CheckForModifiableLvalue(E, BuiltinLoc, *this)) |
| 14310 | return ExprError(); |
| 14311 | } |
| 14312 | } |
| 14313 | |
| 14314 | if (!IsMS && !E->isTypeDependent() && |
| 14315 | !Context.hasSameType(VaListType, E->getType())) |
| 14316 | return ExprError( |
| 14317 | Diag(E->getBeginLoc(), |
| 14318 | diag::err_first_argument_to_va_arg_not_of_type_va_list) |
| 14319 | << OrigExpr->getType() << E->getSourceRange()); |
| 14320 | |
| 14321 | if (!TInfo->getType()->isDependentType()) { |
| 14322 | if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), |
| 14323 | diag::err_second_parameter_to_va_arg_incomplete, |
| 14324 | TInfo->getTypeLoc())) |
| 14325 | return ExprError(); |
| 14326 | |
| 14327 | if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), |
| 14328 | TInfo->getType(), |
| 14329 | diag::err_second_parameter_to_va_arg_abstract, |
| 14330 | TInfo->getTypeLoc())) |
| 14331 | return ExprError(); |
| 14332 | |
| 14333 | if (!TInfo->getType().isPODType(Context)) { |
| 14334 | Diag(TInfo->getTypeLoc().getBeginLoc(), |
| 14335 | TInfo->getType()->isObjCLifetimeType() |
| 14336 | ? diag::warn_second_parameter_to_va_arg_ownership_qualified |
| 14337 | : diag::warn_second_parameter_to_va_arg_not_pod) |
| 14338 | << TInfo->getType() |
| 14339 | << TInfo->getTypeLoc().getSourceRange(); |
| 14340 | } |
| 14341 | |
| 14342 | // Check for va_arg where arguments of the given type will be promoted |
| 14343 | // (i.e. this va_arg is guaranteed to have undefined behavior). |
| 14344 | QualType PromoteType; |
| 14345 | if (TInfo->getType()->isPromotableIntegerType()) { |
| 14346 | PromoteType = Context.getPromotedIntegerType(TInfo->getType()); |
| 14347 | if (Context.typesAreCompatible(PromoteType, TInfo->getType())) |
| 14348 | PromoteType = QualType(); |
| 14349 | } |
| 14350 | if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) |
| 14351 | PromoteType = Context.DoubleTy; |
| 14352 | if (!PromoteType.isNull()) |
| 14353 | DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, |
| 14354 | PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) |
| 14355 | << TInfo->getType() |
| 14356 | << PromoteType |
| 14357 | << TInfo->getTypeLoc().getSourceRange()); |
| 14358 | } |
| 14359 | |
| 14360 | QualType T = TInfo->getType().getNonLValueExprType(Context); |
| 14361 | return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); |
| 14362 | } |
| 14363 | |
| 14364 | ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { |
| 14365 | // The type of __null will be int or long, depending on the size of |
| 14366 | // pointers on the target. |
| 14367 | QualType Ty; |
| 14368 | const auto& TI = Context.getTargetInfo(); |
| 14369 | unsigned pw = TI.getPointerWidth(0); |
| 14370 | if (TI.areAllPointersCapabilities() && pw == TI.getIntCapWidth()) |
| 14371 | Ty = Context.IntCapTy; |
| 14372 | else if (pw == TI.getIntWidth()) |
| 14373 | Ty = Context.IntTy; |
| 14374 | else if (pw == TI.getLongWidth()) |
| 14375 | Ty = Context.LongTy; |
| 14376 | else if (pw == TI.getLongLongWidth()) |
| 14377 | Ty = Context.LongLongTy; |
| 14378 | else { |
| 14379 | llvm_unreachable("I don't know size of pointer!" ); |
| 14380 | } |
| 14381 | |
| 14382 | return new (Context) GNUNullExpr(Ty, TokenLoc); |
| 14383 | } |
| 14384 | |
| 14385 | ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, |
| 14386 | SourceLocation BuiltinLoc, |
| 14387 | SourceLocation RPLoc) { |
| 14388 | return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); |
| 14389 | } |
| 14390 | |
| 14391 | ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, |
| 14392 | SourceLocation BuiltinLoc, |
| 14393 | SourceLocation RPLoc, |
| 14394 | DeclContext *ParentContext) { |
| 14395 | return new (Context) |
| 14396 | SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); |
| 14397 | } |
| 14398 | |
| 14399 | bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, |
| 14400 | bool Diagnose) { |
| 14401 | if (!getLangOpts().ObjC) |
| 14402 | return false; |
| 14403 | |
| 14404 | const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); |
| 14405 | if (!PT) |
| 14406 | return false; |
| 14407 | |
| 14408 | if (!PT->isObjCIdType()) { |
| 14409 | // Check if the destination is the 'NSString' interface. |
| 14410 | const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); |
| 14411 | if (!ID || !ID->getIdentifier()->isStr("NSString" )) |
| 14412 | return false; |
| 14413 | } |
| 14414 | |
| 14415 | // Ignore any parens, implicit casts (should only be |
| 14416 | // array-to-pointer decays), and not-so-opaque values. The last is |
| 14417 | // important for making this trigger for property assignments. |
| 14418 | Expr *SrcExpr = Exp->IgnoreParenImpCasts(); |
| 14419 | if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) |
| 14420 | if (OV->getSourceExpr()) |
| 14421 | SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); |
| 14422 | |
| 14423 | StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); |
| 14424 | if (!SL || !SL->isAscii()) |
| 14425 | return false; |
| 14426 | if (Diagnose) { |
| 14427 | Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) |
| 14428 | << FixItHint::CreateInsertion(SL->getBeginLoc(), "@" ); |
| 14429 | Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); |
| 14430 | } |
| 14431 | return true; |
| 14432 | } |
| 14433 | |
| 14434 | static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, |
| 14435 | const Expr *SrcExpr) { |
| 14436 | if (!DstType->isFunctionPointerType() || |
| 14437 | !SrcExpr->getType()->isFunctionType()) |
| 14438 | return false; |
| 14439 | |
| 14440 | auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); |
| 14441 | if (!DRE) |
| 14442 | return false; |
| 14443 | |
| 14444 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); |
| 14445 | if (!FD) |
| 14446 | return false; |
| 14447 | |
| 14448 | return !S.checkAddressOfFunctionIsAvailable(FD, |
| 14449 | /*Complain=*/true, |
| 14450 | SrcExpr->getBeginLoc()); |
| 14451 | } |
| 14452 | |
| 14453 | static void diagnoseBadVariadicFunctionPointerAssignment(Sema &S, |
| 14454 | SourceLocation Loc, |
| 14455 | QualType SrcType, |
| 14456 | QualType DstType, |
| 14457 | Expr* SrcExpr) { |
| 14458 | const FunctionType *DstFnTy = |
| 14459 | DstType->getPointeeType()->getAs<FunctionType>(); |
| 14460 | |
| 14461 | const FunctionType *SrcFnTy = nullptr; |
| 14462 | if (SrcType->isFunctionPointerType()) |
| 14463 | SrcFnTy = SrcType->getPointeeType()->getAs<FunctionType>(); |
| 14464 | else |
| 14465 | SrcFnTy = SrcType->getAs<FunctionType>(); |
| 14466 | // TODO: also diagnose any variadic to non-variadic |
| 14467 | // TODO: don't warn about zero-arg function |
| 14468 | if (!SrcFnTy) |
| 14469 | return; // Should give an invalid pointer to function warning anyway |
| 14470 | |
| 14471 | FunctionDecl* FuncDecl = nullptr; |
| 14472 | // Avoid warnings for K&R functions where we actually know the prototype: |
| 14473 | if (auto *UO = dyn_cast<UnaryOperator>(SrcExpr->IgnoreImplicit())) { |
| 14474 | // look through &foo to find the actual function |
| 14475 | if (UO->getOpcode() == UO_AddrOf) |
| 14476 | SrcExpr = UO->getSubExpr(); |
| 14477 | } |
| 14478 | if (auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreImplicit())) { |
| 14479 | FuncDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); |
| 14480 | } |
| 14481 | |
| 14482 | enum class CCType { NoProto, Variadic, FixedArg, Invalid }; |
| 14483 | CCType SrcCCType = CCType::Invalid; |
| 14484 | if (SrcFnTy->isFunctionNoProtoType()) { |
| 14485 | // Type is noproto but we might have a decl with the real prototype: |
| 14486 | if (FuncDecl) |
| 14487 | SrcFnTy = FuncDecl->getType()->getAs<FunctionType>(); |
| 14488 | // Now check again to see if it is still a noproto type |
| 14489 | if (SrcFnTy->isFunctionNoProtoType()) |
| 14490 | SrcCCType = CCType::NoProto; |
| 14491 | } |
| 14492 | if (auto *SrcProto = SrcFnTy->getAs<FunctionProtoType>()) { |
| 14493 | // assigning a function without parameters is fine since there will never be |
| 14494 | // any confusion between on-stack and in-register arguments |
| 14495 | if (SrcProto->getNumParams() == 0) |
| 14496 | return; |
| 14497 | SrcCCType = SrcProto->isVariadic() ? CCType::Variadic : CCType::FixedArg; |
| 14498 | } |
| 14499 | CCType DstCCType = CCType::Invalid; |
| 14500 | if (DstFnTy->isFunctionNoProtoType()) |
| 14501 | DstCCType = CCType::NoProto; |
| 14502 | else if (auto *DstProto = DstFnTy->getAs<FunctionProtoType>()) { |
| 14503 | DstCCType = DstProto->isVariadic() ? CCType::Variadic : CCType::FixedArg; |
| 14504 | } |
| 14505 | assert(SrcCCType != CCType::Invalid); |
| 14506 | assert(DstCCType != CCType::Invalid); |
| 14507 | |
| 14508 | if (SrcCCType != DstCCType) { |
| 14509 | // converting variadic to non-variadic is an error by default, the other is |
| 14510 | // a pedantic warning that is often a false positive |
| 14511 | unsigned DiagID = diag::warn_mips_cheri_fnptr_proto_noproto_conversion; |
| 14512 | unsigned ExplainID = diag::note_mips_cheri_func_noproto_explanation; |
| 14513 | if (SrcCCType == CCType::Variadic || DstCCType == CCType::Variadic) { |
| 14514 | DiagID = diag::warn_mips_cheri_fnptr_variadic_nonvariadic_conversion; |
| 14515 | ExplainID = diag::note_mips_cheri_func_variadic_explanation; |
| 14516 | } |
| 14517 | S.Diag(Loc, DiagID) << (int)SrcCCType << SrcType << (int)DstCCType |
| 14518 | << DstType; |
| 14519 | S.Diag(Loc, ExplainID); |
| 14520 | if (FuncDecl) |
| 14521 | S.Diag(FuncDecl->getBeginLoc(), diag::note_callee_decl) << FuncDecl; |
| 14522 | } |
| 14523 | } |
| 14524 | |
| 14525 | bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, |
| 14526 | SourceLocation Loc, |
| 14527 | QualType DstType, QualType SrcType, |
| 14528 | Expr *SrcExpr, AssignmentAction Action, |
| 14529 | bool *Complained) { |
| 14530 | if (Complained) |
| 14531 | *Complained = false; |
| 14532 | |
| 14533 | // Decode the result (notice that AST's are still created for extensions). |
| 14534 | bool CheckInferredResultType = false; |
| 14535 | bool isInvalid = false; |
| 14536 | unsigned DiagKind = 0; |
| 14537 | FixItHint Hint; |
| 14538 | ConversionFixItGenerator ConvHints; |
| 14539 | bool MayHaveConvFixit = false; |
| 14540 | bool MayHaveFunctionDiff = false; |
| 14541 | const ObjCInterfaceDecl *IFace = nullptr; |
| 14542 | const ObjCProtocolDecl *PDecl = nullptr; |
| 14543 | |
| 14544 | // Warn when assigning non-variadic functions to variadic function pointers |
| 14545 | // and the other way around |
| 14546 | // TODO: this should probably be upstreamed as it is not CHERI specific |
| 14547 | // TODO: only for Context.getTargetInfo().areAllPointersCapabilities()? |
| 14548 | // Note: we need to do this even if ConvTy == compatible since pointers without |
| 14549 | // prototypes can be assigned to from any function pointer type |
| 14550 | if (DstType->isFunctionPointerType()) |
| 14551 | diagnoseBadVariadicFunctionPointerAssignment(*this, Loc, SrcType, DstType, SrcExpr); |
| 14552 | |
| 14553 | switch (ConvTy) { |
| 14554 | case Compatible: |
| 14555 | DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); |
| 14556 | return false; |
| 14557 | |
| 14558 | case PointerToInt: |
| 14559 | DiagKind = diag::ext_typecheck_convert_pointer_int; |
| 14560 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); |
| 14561 | MayHaveConvFixit = true; |
| 14562 | break; |
| 14563 | case IntToPointer: |
| 14564 | DiagKind = diag::ext_typecheck_convert_int_pointer; |
| 14565 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); |
| 14566 | MayHaveConvFixit = true; |
| 14567 | break; |
| 14568 | case IncompatiblePointer: |
| 14569 | if (Action == AA_Passing_CFAudited) |
| 14570 | DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; |
| 14571 | else if (SrcType->isFunctionPointerType() && |
| 14572 | DstType->isFunctionPointerType()) |
| 14573 | DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; |
| 14574 | else |
| 14575 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer; |
| 14576 | |
| 14577 | CheckInferredResultType = DstType->isObjCObjectPointerType() && |
| 14578 | SrcType->isObjCObjectPointerType(); |
| 14579 | if (Hint.isNull() && !CheckInferredResultType) { |
| 14580 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); |
| 14581 | } |
| 14582 | else if (CheckInferredResultType) { |
| 14583 | SrcType = SrcType.getUnqualifiedType(); |
| 14584 | DstType = DstType.getUnqualifiedType(); |
| 14585 | } |
| 14586 | MayHaveConvFixit = true; |
| 14587 | break; |
| 14588 | case IncompatiblePointerSign: |
| 14589 | DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; |
| 14590 | break; |
| 14591 | case FunctionVoidPointer: |
| 14592 | DiagKind = diag::ext_typecheck_convert_pointer_void_func; |
| 14593 | break; |
| 14594 | case IncompatiblePointerDiscardsQualifiers: { |
| 14595 | // Perform array-to-pointer decay if necessary. |
| 14596 | if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); |
| 14597 | |
| 14598 | Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); |
| 14599 | Qualifiers rhq = DstType->getPointeeType().getQualifiers(); |
| 14600 | if (lhq.getAddressSpace() != rhq.getAddressSpace()) { |
| 14601 | DiagKind = diag::err_typecheck_incompatible_address_space; |
| 14602 | break; |
| 14603 | |
| 14604 | } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { |
| 14605 | DiagKind = diag::err_typecheck_incompatible_ownership; |
| 14606 | break; |
| 14607 | } |
| 14608 | |
| 14609 | llvm_unreachable("unknown error case for discarding qualifiers!" ); |
| 14610 | // fallthrough |
| 14611 | } |
| 14612 | case CompatiblePointerDiscardsQualifiers: |
| 14613 | // If the qualifiers lost were because we were applying the |
| 14614 | // (deprecated) C++ conversion from a string literal to a char* |
| 14615 | // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: |
| 14616 | // Ideally, this check would be performed in |
| 14617 | // checkPointerTypesForAssignment. However, that would require a |
| 14618 | // bit of refactoring (so that the second argument is an |
| 14619 | // expression, rather than a type), which should be done as part |
| 14620 | // of a larger effort to fix checkPointerTypesForAssignment for |
| 14621 | // C++ semantics. |
| 14622 | if (getLangOpts().CPlusPlus && |
| 14623 | IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) |
| 14624 | return false; |
| 14625 | DiagKind = diag::ext_typecheck_convert_discards_qualifiers; |
| 14626 | break; |
| 14627 | case IncompatibleNestedPointerQualifiers: |
| 14628 | DiagKind = diag::ext_nested_pointer_qualifier_mismatch; |
| 14629 | break; |
| 14630 | case IncompatibleNestedPointerAddressSpaceMismatch: |
| 14631 | DiagKind = diag::err_typecheck_incompatible_nested_address_space; |
| 14632 | break; |
| 14633 | case IntToBlockPointer: |
| 14634 | DiagKind = diag::err_int_to_block_pointer; |
| 14635 | break; |
| 14636 | case IncompatibleBlockPointer: |
| 14637 | DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; |
| 14638 | break; |
| 14639 | case IncompatibleObjCQualifiedId: { |
| 14640 | if (SrcType->isObjCQualifiedIdType()) { |
| 14641 | const ObjCObjectPointerType *srcOPT = |
| 14642 | SrcType->getAs<ObjCObjectPointerType>(); |
| 14643 | for (auto *srcProto : srcOPT->quals()) { |
| 14644 | PDecl = srcProto; |
| 14645 | break; |
| 14646 | } |
| 14647 | if (const ObjCInterfaceType *IFaceT = |
| 14648 | DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) |
| 14649 | IFace = IFaceT->getDecl(); |
| 14650 | } |
| 14651 | else if (DstType->isObjCQualifiedIdType()) { |
| 14652 | const ObjCObjectPointerType *dstOPT = |
| 14653 | DstType->getAs<ObjCObjectPointerType>(); |
| 14654 | for (auto *dstProto : dstOPT->quals()) { |
| 14655 | PDecl = dstProto; |
| 14656 | break; |
| 14657 | } |
| 14658 | if (const ObjCInterfaceType *IFaceT = |
| 14659 | SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) |
| 14660 | IFace = IFaceT->getDecl(); |
| 14661 | } |
| 14662 | DiagKind = diag::warn_incompatible_qualified_id; |
| 14663 | break; |
| 14664 | } |
| 14665 | case IncompatibleVectors: |
| 14666 | DiagKind = diag::warn_incompatible_vectors; |
| 14667 | break; |
| 14668 | case IncompatibleObjCWeakRef: |
| 14669 | DiagKind = diag::err_arc_weak_unavailable_assign; |
| 14670 | break; |
| 14671 | case CHERICapabilityToPointer: |
| 14672 | case PointerToCHERICapability: { |
| 14673 | bool PtrToCap = ConvTy == PointerToCHERICapability; |
| 14674 | |
| 14675 | if (PtrToCap) { |
| 14676 | // first perform array|function to pointer decay |
| 14677 | ExprResult Decayed = DefaultFunctionArrayLvalueConversion(SrcExpr); |
| 14678 | if (Decayed.isInvalid()) { |
| 14679 | isInvalid = true; |
| 14680 | return true; |
| 14681 | break; |
| 14682 | } |
| 14683 | SrcExpr = Decayed.get(); |
| 14684 | SrcType = SrcExpr->getType(); |
| 14685 | if (ImpCastPointerToCHERICapability(SrcType, DstType, SrcExpr, false)) |
| 14686 | return false; |
| 14687 | } |
| 14688 | |
| 14689 | // If we reach here, output an error |
| 14690 | DiagKind = PtrToCap ? diag::err_typecheck_convert_ptr_to_cap |
| 14691 | : diag::err_typecheck_convert_cap_to_ptr; |
| 14692 | MayHaveConvFixit = true; |
| 14693 | isInvalid = true; |
| 14694 | Hint = FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "(__cheri_" + |
| 14695 | std::string(PtrToCap ? "to" : "from" ) + |
| 14696 | "cap " + DstType.getAsString() + ")" ); |
| 14697 | Diag(Loc, DiagKind) << SrcType << DstType << false << Hint; |
| 14698 | return true; |
| 14699 | break; |
| 14700 | } |
| 14701 | case Incompatible: |
| 14702 | if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { |
| 14703 | if (Complained) |
| 14704 | *Complained = true; |
| 14705 | return true; |
| 14706 | } |
| 14707 | |
| 14708 | // CHERI: in the case of implicit conversion of address-of expressions to capabilities, |
| 14709 | // output error message here if the types are not compatible, so that we |
| 14710 | // get the same error message for both C and C++. |
| 14711 | if (SrcType->isPointerType() |
| 14712 | && !SrcType->isCHERICapabilityType(Context, false) |
| 14713 | && DstType->isCHERICapabilityType(Context, false)) { |
| 14714 | if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(SrcExpr)) { |
| 14715 | if (UnOp->getOpcode() == UO_AddrOf) { |
| 14716 | Diag(SrcExpr->getExprLoc(), diag::err_typecheck_convert_ptr_to_cap_unrelated_type) |
| 14717 | << SrcType << DstType << false; |
| 14718 | return true; |
| 14719 | } |
| 14720 | } |
| 14721 | } |
| 14722 | |
| 14723 | DiagKind = diag::err_typecheck_convert_incompatible; |
| 14724 | ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); |
| 14725 | MayHaveConvFixit = true; |
| 14726 | isInvalid = true; |
| 14727 | MayHaveFunctionDiff = true; |
| 14728 | break; |
| 14729 | } |
| 14730 | |
| 14731 | QualType FirstType, SecondType; |
| 14732 | switch (Action) { |
| 14733 | case AA_Assigning: |
| 14734 | case AA_Initializing: |
| 14735 | // The destination type comes first. |
| 14736 | FirstType = DstType; |
| 14737 | SecondType = SrcType; |
| 14738 | break; |
| 14739 | |
| 14740 | case AA_Returning: |
| 14741 | case AA_Passing: |
| 14742 | case AA_Passing_CFAudited: |
| 14743 | case AA_Converting: |
| 14744 | case AA_Sending: |
| 14745 | case AA_Casting: |
| 14746 | // The source type comes first. |
| 14747 | FirstType = SrcType; |
| 14748 | SecondType = DstType; |
| 14749 | break; |
| 14750 | } |
| 14751 | |
| 14752 | PartialDiagnostic FDiag = PDiag(DiagKind); |
| 14753 | if (Action == AA_Passing_CFAudited) |
| 14754 | FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); |
| 14755 | else |
| 14756 | FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); |
| 14757 | |
| 14758 | // If we can fix the conversion, suggest the FixIts. |
| 14759 | assert(ConvHints.isNull() || Hint.isNull()); |
| 14760 | if (!ConvHints.isNull()) { |
| 14761 | for (FixItHint &H : ConvHints.Hints) |
| 14762 | FDiag << H; |
| 14763 | } else { |
| 14764 | FDiag << Hint; |
| 14765 | } |
| 14766 | if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } |
| 14767 | |
| 14768 | if (MayHaveFunctionDiff) |
| 14769 | HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); |
| 14770 | |
| 14771 | Diag(Loc, FDiag); |
| 14772 | if (DiagKind == diag::warn_incompatible_qualified_id && |
| 14773 | PDecl && IFace && !IFace->hasDefinition()) |
| 14774 | Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) |
| 14775 | << IFace << PDecl; |
| 14776 | |
| 14777 | if (SecondType == Context.OverloadTy) |
| 14778 | NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, |
| 14779 | FirstType, /*TakingAddress=*/true); |
| 14780 | |
| 14781 | if (CheckInferredResultType) |
| 14782 | EmitRelatedResultTypeNote(SrcExpr); |
| 14783 | |
| 14784 | if (Action == AA_Returning && ConvTy == IncompatiblePointer) |
| 14785 | EmitRelatedResultTypeNoteForReturn(DstType); |
| 14786 | |
| 14787 | if (Complained) |
| 14788 | *Complained = true; |
| 14789 | return isInvalid; |
| 14790 | } |
| 14791 | |
| 14792 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
| 14793 | llvm::APSInt *Result) { |
| 14794 | class SimpleICEDiagnoser : public VerifyICEDiagnoser { |
| 14795 | public: |
| 14796 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { |
| 14797 | S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; |
| 14798 | } |
| 14799 | } Diagnoser; |
| 14800 | |
| 14801 | return VerifyIntegerConstantExpression(E, Result, Diagnoser); |
| 14802 | } |
| 14803 | |
| 14804 | ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, |
| 14805 | llvm::APSInt *Result, |
| 14806 | unsigned DiagID, |
| 14807 | bool AllowFold) { |
| 14808 | class IDDiagnoser : public VerifyICEDiagnoser { |
| 14809 | unsigned DiagID; |
| 14810 | |
| 14811 | public: |
| 14812 | IDDiagnoser(unsigned DiagID) |
| 14813 | : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } |
| 14814 | |
| 14815 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { |
| 14816 | S.Diag(Loc, DiagID) << SR; |
| 14817 | } |
| 14818 | } Diagnoser(DiagID); |
| 14819 | |
| 14820 | return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); |
| 14821 | } |
| 14822 | |
| 14823 | void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, |
| 14824 | SourceRange SR) { |
| 14825 | S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; |
| 14826 | } |
| 14827 | |
| 14828 | ExprResult |
| 14829 | Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, |
| 14830 | VerifyICEDiagnoser &Diagnoser, |
| 14831 | bool AllowFold) { |
| 14832 | SourceLocation DiagLoc = E->getBeginLoc(); |
| 14833 | |
| 14834 | if (getLangOpts().CPlusPlus11) { |
| 14835 | // C++11 [expr.const]p5: |
| 14836 | // If an expression of literal class type is used in a context where an |
| 14837 | // integral constant expression is required, then that class type shall |
| 14838 | // have a single non-explicit conversion function to an integral or |
| 14839 | // unscoped enumeration type |
| 14840 | ExprResult Converted; |
| 14841 | class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { |
| 14842 | public: |
| 14843 | CXX11ConvertDiagnoser(bool Silent) |
| 14844 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, |
| 14845 | Silent, true) {} |
| 14846 | |
| 14847 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
| 14848 | QualType T) override { |
| 14849 | return S.Diag(Loc, diag::err_ice_not_integral) << T; |
| 14850 | } |
| 14851 | |
| 14852 | SemaDiagnosticBuilder diagnoseIncomplete( |
| 14853 | Sema &S, SourceLocation Loc, QualType T) override { |
| 14854 | return S.Diag(Loc, diag::err_ice_incomplete_type) << T; |
| 14855 | } |
| 14856 | |
| 14857 | SemaDiagnosticBuilder diagnoseExplicitConv( |
| 14858 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
| 14859 | return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; |
| 14860 | } |
| 14861 | |
| 14862 | SemaDiagnosticBuilder noteExplicitConv( |
| 14863 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
| 14864 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) |
| 14865 | << ConvTy->isEnumeralType() << ConvTy; |
| 14866 | } |
| 14867 | |
| 14868 | SemaDiagnosticBuilder diagnoseAmbiguous( |
| 14869 | Sema &S, SourceLocation Loc, QualType T) override { |
| 14870 | return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; |
| 14871 | } |
| 14872 | |
| 14873 | SemaDiagnosticBuilder noteAmbiguous( |
| 14874 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
| 14875 | return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) |
| 14876 | << ConvTy->isEnumeralType() << ConvTy; |
| 14877 | } |
| 14878 | |
| 14879 | SemaDiagnosticBuilder diagnoseConversion( |
| 14880 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
| 14881 | llvm_unreachable("conversion functions are permitted" ); |
| 14882 | } |
| 14883 | } ConvertDiagnoser(Diagnoser.Suppress); |
| 14884 | |
| 14885 | Converted = PerformContextualImplicitConversion(DiagLoc, E, |
| 14886 | ConvertDiagnoser); |
| 14887 | if (Converted.isInvalid()) |
| 14888 | return Converted; |
| 14889 | E = Converted.get(); |
| 14890 | if (!E->getType()->isIntegralOrUnscopedEnumerationType()) |
| 14891 | return ExprError(); |
| 14892 | } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { |
| 14893 | // An ICE must be of integral or unscoped enumeration type. |
| 14894 | if (!Diagnoser.Suppress) |
| 14895 | Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); |
| 14896 | return ExprError(); |
| 14897 | } |
| 14898 | |
| 14899 | if (!isa<ConstantExpr>(E)) |
| 14900 | E = ConstantExpr::Create(Context, E); |
| 14901 | |
| 14902 | // Circumvent ICE checking in C++11 to avoid evaluating the expression twice |
| 14903 | // in the non-ICE case. |
| 14904 | if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { |
| 14905 | if (Result) |
| 14906 | *Result = E->EvaluateKnownConstIntCheckOverflow(Context); |
| 14907 | return E; |
| 14908 | } |
| 14909 | |
| 14910 | Expr::EvalResult EvalResult; |
| 14911 | SmallVector<PartialDiagnosticAt, 8> Notes; |
| 14912 | EvalResult.Diag = &Notes; |
| 14913 | |
| 14914 | // Try to evaluate the expression, and produce diagnostics explaining why it's |
| 14915 | // not a constant expression as a side-effect. |
| 14916 | bool Folded = E->EvaluateAsRValue(EvalResult, Context) && |
| 14917 | EvalResult.Val.isInt() && !EvalResult.HasSideEffects; |
| 14918 | |
| 14919 | // In C++11, we can rely on diagnostics being produced for any expression |
| 14920 | // which is not a constant expression. If no diagnostics were produced, then |
| 14921 | // this is a constant expression. |
| 14922 | if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { |
| 14923 | if (Result) |
| 14924 | *Result = EvalResult.Val.getInt(); |
| 14925 | return E; |
| 14926 | } |
| 14927 | |
| 14928 | // If our only note is the usual "invalid subexpression" note, just point |
| 14929 | // the caret at its location rather than producing an essentially |
| 14930 | // redundant note. |
| 14931 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
| 14932 | diag::note_invalid_subexpr_in_const_expr) { |
| 14933 | DiagLoc = Notes[0].first; |
| 14934 | Notes.clear(); |
| 14935 | } |
| 14936 | |
| 14937 | if (!Folded || !AllowFold) { |
| 14938 | if (!Diagnoser.Suppress) { |
| 14939 | Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); |
| 14940 | for (const PartialDiagnosticAt &Note : Notes) |
| 14941 | Diag(Note.first, Note.second); |
| 14942 | } |
| 14943 | |
| 14944 | return ExprError(); |
| 14945 | } |
| 14946 | |
| 14947 | Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); |
| 14948 | for (const PartialDiagnosticAt &Note : Notes) |
| 14949 | Diag(Note.first, Note.second); |
| 14950 | |
| 14951 | if (Result) |
| 14952 | *Result = EvalResult.Val.getInt(); |
| 14953 | return E; |
| 14954 | } |
| 14955 | |
| 14956 | namespace { |
| 14957 | // Handle the case where we conclude a expression which we speculatively |
| 14958 | // considered to be unevaluated is actually evaluated. |
| 14959 | class TransformToPE : public TreeTransform<TransformToPE> { |
| 14960 | typedef TreeTransform<TransformToPE> BaseTransform; |
| 14961 | |
| 14962 | public: |
| 14963 | TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } |
| 14964 | |
| 14965 | // Make sure we redo semantic analysis |
| 14966 | bool AlwaysRebuild() { return true; } |
| 14967 | bool ReplacingOriginal() { return true; } |
| 14968 | |
| 14969 | // We need to special-case DeclRefExprs referring to FieldDecls which |
| 14970 | // are not part of a member pointer formation; normal TreeTransforming |
| 14971 | // doesn't catch this case because of the way we represent them in the AST. |
| 14972 | // FIXME: This is a bit ugly; is it really the best way to handle this |
| 14973 | // case? |
| 14974 | // |
| 14975 | // Error on DeclRefExprs referring to FieldDecls. |
| 14976 | ExprResult TransformDeclRefExpr(DeclRefExpr *E) { |
| 14977 | if (isa<FieldDecl>(E->getDecl()) && |
| 14978 | !SemaRef.isUnevaluatedContext()) |
| 14979 | return SemaRef.Diag(E->getLocation(), |
| 14980 | diag::err_invalid_non_static_member_use) |
| 14981 | << E->getDecl() << E->getSourceRange(); |
| 14982 | |
| 14983 | return BaseTransform::TransformDeclRefExpr(E); |
| 14984 | } |
| 14985 | |
| 14986 | // Exception: filter out member pointer formation |
| 14987 | ExprResult TransformUnaryOperator(UnaryOperator *E) { |
| 14988 | if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) |
| 14989 | return E; |
| 14990 | |
| 14991 | return BaseTransform::TransformUnaryOperator(E); |
| 14992 | } |
| 14993 | |
| 14994 | // The body of a lambda-expression is in a separate expression evaluation |
| 14995 | // context so never needs to be transformed. |
| 14996 | // FIXME: Ideally we wouldn't transform the closure type either, and would |
| 14997 | // just recreate the capture expressions and lambda expression. |
| 14998 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
| 14999 | return SkipLambdaBody(E, Body); |
| 15000 | } |
| 15001 | }; |
| 15002 | } |
| 15003 | |
| 15004 | ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { |
| 15005 | assert(isUnevaluatedContext() && |
| 15006 | "Should only transform unevaluated expressions" ); |
| 15007 | ExprEvalContexts.back().Context = |
| 15008 | ExprEvalContexts[ExprEvalContexts.size()-2].Context; |
| 15009 | if (isUnevaluatedContext()) |
| 15010 | return E; |
| 15011 | return TransformToPE(*this).TransformExpr(E); |
| 15012 | } |
| 15013 | |
| 15014 | void |
| 15015 | Sema::PushExpressionEvaluationContext( |
| 15016 | ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, |
| 15017 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
| 15018 | ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, |
| 15019 | LambdaContextDecl, ExprContext); |
| 15020 | Cleanup.reset(); |
| 15021 | if (!MaybeODRUseExprs.empty()) |
| 15022 | std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); |
| 15023 | } |
| 15024 | |
| 15025 | void |
| 15026 | Sema::PushExpressionEvaluationContext( |
| 15027 | ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, |
| 15028 | ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { |
| 15029 | Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; |
| 15030 | PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); |
| 15031 | } |
| 15032 | |
| 15033 | namespace { |
| 15034 | |
| 15035 | const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { |
| 15036 | PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); |
| 15037 | if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { |
| 15038 | if (E->getOpcode() == UO_Deref) |
| 15039 | return CheckPossibleDeref(S, E->getSubExpr()); |
| 15040 | } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { |
| 15041 | return CheckPossibleDeref(S, E->getBase()); |
| 15042 | } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { |
| 15043 | return CheckPossibleDeref(S, E->getBase()); |
| 15044 | } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { |
| 15045 | QualType Inner; |
| 15046 | QualType Ty = E->getType(); |
| 15047 | if (const auto *Ptr = Ty->getAs<PointerType>()) |
| 15048 | Inner = Ptr->getPointeeType(); |
| 15049 | else if (const auto *Arr = S.Context.getAsArrayType(Ty)) |
| 15050 | Inner = Arr->getElementType(); |
| 15051 | else |
| 15052 | return nullptr; |
| 15053 | |
| 15054 | if (Inner->hasAttr(attr::NoDeref)) |
| 15055 | return E; |
| 15056 | } |
| 15057 | return nullptr; |
| 15058 | } |
| 15059 | |
| 15060 | } // namespace |
| 15061 | |
| 15062 | void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { |
| 15063 | for (const Expr *E : Rec.PossibleDerefs) { |
| 15064 | const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); |
| 15065 | if (DeclRef) { |
| 15066 | const ValueDecl *Decl = DeclRef->getDecl(); |
| 15067 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) |
| 15068 | << Decl->getName() << E->getSourceRange(); |
| 15069 | Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); |
| 15070 | } else { |
| 15071 | Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) |
| 15072 | << E->getSourceRange(); |
| 15073 | } |
| 15074 | } |
| 15075 | Rec.PossibleDerefs.clear(); |
| 15076 | } |
| 15077 | |
| 15078 | void Sema::PopExpressionEvaluationContext() { |
| 15079 | ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); |
| 15080 | unsigned NumTypos = Rec.NumTypos; |
| 15081 | |
| 15082 | if (!Rec.Lambdas.empty()) { |
| 15083 | using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; |
| 15084 | if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || |
| 15085 | (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { |
| 15086 | unsigned D; |
| 15087 | if (Rec.isUnevaluated()) { |
| 15088 | // C++11 [expr.prim.lambda]p2: |
| 15089 | // A lambda-expression shall not appear in an unevaluated operand |
| 15090 | // (Clause 5). |
| 15091 | D = diag::err_lambda_unevaluated_operand; |
| 15092 | } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { |
| 15093 | // C++1y [expr.const]p2: |
| 15094 | // A conditional-expression e is a core constant expression unless the |
| 15095 | // evaluation of e, following the rules of the abstract machine, would |
| 15096 | // evaluate [...] a lambda-expression. |
| 15097 | D = diag::err_lambda_in_constant_expression; |
| 15098 | } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { |
| 15099 | // C++17 [expr.prim.lamda]p2: |
| 15100 | // A lambda-expression shall not appear [...] in a template-argument. |
| 15101 | D = diag::err_lambda_in_invalid_context; |
| 15102 | } else |
| 15103 | llvm_unreachable("Couldn't infer lambda error message." ); |
| 15104 | |
| 15105 | for (const auto *L : Rec.Lambdas) |
| 15106 | Diag(L->getBeginLoc(), D); |
| 15107 | } |
| 15108 | } |
| 15109 | |
| 15110 | WarnOnPendingNoDerefs(Rec); |
| 15111 | |
| 15112 | // When are coming out of an unevaluated context, clear out any |
| 15113 | // temporaries that we may have created as part of the evaluation of |
| 15114 | // the expression in that context: they aren't relevant because they |
| 15115 | // will never be constructed. |
| 15116 | if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { |
| 15117 | ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, |
| 15118 | ExprCleanupObjects.end()); |
| 15119 | Cleanup = Rec.ParentCleanup; |
| 15120 | CleanupVarDeclMarking(); |
| 15121 | std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); |
| 15122 | // Otherwise, merge the contexts together. |
| 15123 | } else { |
| 15124 | Cleanup.mergeFrom(Rec.ParentCleanup); |
| 15125 | MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), |
| 15126 | Rec.SavedMaybeODRUseExprs.end()); |
| 15127 | } |
| 15128 | |
| 15129 | // Pop the current expression evaluation context off the stack. |
| 15130 | ExprEvalContexts.pop_back(); |
| 15131 | |
| 15132 | // The global expression evaluation context record is never popped. |
| 15133 | ExprEvalContexts.back().NumTypos += NumTypos; |
| 15134 | } |
| 15135 | |
| 15136 | void Sema::DiscardCleanupsInEvaluationContext() { |
| 15137 | ExprCleanupObjects.erase( |
| 15138 | ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, |
| 15139 | ExprCleanupObjects.end()); |
| 15140 | Cleanup.reset(); |
| 15141 | MaybeODRUseExprs.clear(); |
| 15142 | } |
| 15143 | |
| 15144 | ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { |
| 15145 | ExprResult Result = CheckPlaceholderExpr(E); |
| 15146 | if (Result.isInvalid()) |
| 15147 | return ExprError(); |
| 15148 | E = Result.get(); |
| 15149 | if (!E->getType()->isVariablyModifiedType()) |
| 15150 | return E; |
| 15151 | return TransformToPotentiallyEvaluated(E); |
| 15152 | } |
| 15153 | |
| 15154 | /// Are we in a context that is potentially constant evaluated per C++20 |
| 15155 | /// [expr.const]p12? |
| 15156 | static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { |
| 15157 | /// C++2a [expr.const]p12: |
| 15158 | // An expression or conversion is potentially constant evaluated if it is |
| 15159 | switch (SemaRef.ExprEvalContexts.back().Context) { |
| 15160 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: |
| 15161 | // -- a manifestly constant-evaluated expression, |
| 15162 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: |
| 15163 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
| 15164 | case Sema::ExpressionEvaluationContext::DiscardedStatement: |
| 15165 | // -- a potentially-evaluated expression, |
| 15166 | case Sema::ExpressionEvaluationContext::UnevaluatedList: |
| 15167 | // -- an immediate subexpression of a braced-init-list, |
| 15168 | |
| 15169 | // -- [FIXME] an expression of the form & cast-expression that occurs |
| 15170 | // within a templated entity |
| 15171 | // -- a subexpression of one of the above that is not a subexpression of |
| 15172 | // a nested unevaluated operand. |
| 15173 | return true; |
| 15174 | |
| 15175 | case Sema::ExpressionEvaluationContext::Unevaluated: |
| 15176 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: |
| 15177 | // Expressions in this context are never evaluated. |
| 15178 | return false; |
| 15179 | } |
| 15180 | llvm_unreachable("Invalid context" ); |
| 15181 | } |
| 15182 | |
| 15183 | /// Return true if this function has a calling convention that requires mangling |
| 15184 | /// in the size of the parameter pack. |
| 15185 | static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { |
| 15186 | // These manglings don't do anything on non-Windows or non-x86 platforms, so |
| 15187 | // we don't need parameter type sizes. |
| 15188 | const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); |
| 15189 | if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && |
| 15190 | TT.getArch() != llvm::Triple::x86_64)) |
| 15191 | return false; |
| 15192 | |
| 15193 | // If this is C++ and this isn't an extern "C" function, parameters do not |
| 15194 | // need to be complete. In this case, C++ mangling will apply, which doesn't |
| 15195 | // use the size of the parameters. |
| 15196 | if (S.getLangOpts().CPlusPlus && !FD->isExternC()) |
| 15197 | return false; |
| 15198 | |
| 15199 | // Stdcall, fastcall, and vectorcall need this special treatment. |
| 15200 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
| 15201 | switch (CC) { |
| 15202 | case CC_X86StdCall: |
| 15203 | case CC_X86FastCall: |
| 15204 | case CC_X86VectorCall: |
| 15205 | return true; |
| 15206 | default: |
| 15207 | break; |
| 15208 | } |
| 15209 | return false; |
| 15210 | } |
| 15211 | |
| 15212 | /// Require that all of the parameter types of function be complete. Normally, |
| 15213 | /// parameter types are only required to be complete when a function is called |
| 15214 | /// or defined, but to mangle functions with certain calling conventions, the |
| 15215 | /// mangler needs to know the size of the parameter list. In this situation, |
| 15216 | /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles |
| 15217 | /// the function as _foo@0, i.e. zero bytes of parameters, which will usually |
| 15218 | /// result in a linker error. Clang doesn't implement this behavior, and instead |
| 15219 | /// attempts to error at compile time. |
| 15220 | static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, |
| 15221 | SourceLocation Loc) { |
| 15222 | class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { |
| 15223 | FunctionDecl *FD; |
| 15224 | ParmVarDecl *Param; |
| 15225 | |
| 15226 | public: |
| 15227 | ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) |
| 15228 | : FD(FD), Param(Param) {} |
| 15229 | |
| 15230 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
| 15231 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
| 15232 | StringRef CCName; |
| 15233 | switch (CC) { |
| 15234 | case CC_X86StdCall: |
| 15235 | CCName = "stdcall" ; |
| 15236 | break; |
| 15237 | case CC_X86FastCall: |
| 15238 | CCName = "fastcall" ; |
| 15239 | break; |
| 15240 | case CC_X86VectorCall: |
| 15241 | CCName = "vectorcall" ; |
| 15242 | break; |
| 15243 | default: |
| 15244 | llvm_unreachable("CC does not need mangling" ); |
| 15245 | } |
| 15246 | |
| 15247 | S.Diag(Loc, diag::err_cconv_incomplete_param_type) |
| 15248 | << Param->getDeclName() << FD->getDeclName() << CCName; |
| 15249 | } |
| 15250 | }; |
| 15251 | |
| 15252 | for (ParmVarDecl *Param : FD->parameters()) { |
| 15253 | ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); |
| 15254 | S.RequireCompleteType(Loc, Param->getType(), Diagnoser); |
| 15255 | } |
| 15256 | } |
| 15257 | |
| 15258 | namespace { |
| 15259 | enum class OdrUseContext { |
| 15260 | /// Declarations in this context are not odr-used. |
| 15261 | None, |
| 15262 | /// Declarations in this context are formally odr-used, but this is a |
| 15263 | /// dependent context. |
| 15264 | Dependent, |
| 15265 | /// Declarations in this context are odr-used but not actually used (yet). |
| 15266 | FormallyOdrUsed, |
| 15267 | /// Declarations in this context are used. |
| 15268 | Used |
| 15269 | }; |
| 15270 | } |
| 15271 | |
| 15272 | /// Are we within a context in which references to resolved functions or to |
| 15273 | /// variables result in odr-use? |
| 15274 | static OdrUseContext isOdrUseContext(Sema &SemaRef) { |
| 15275 | OdrUseContext Result; |
| 15276 | |
| 15277 | switch (SemaRef.ExprEvalContexts.back().Context) { |
| 15278 | case Sema::ExpressionEvaluationContext::Unevaluated: |
| 15279 | case Sema::ExpressionEvaluationContext::UnevaluatedList: |
| 15280 | case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: |
| 15281 | return OdrUseContext::None; |
| 15282 | |
| 15283 | case Sema::ExpressionEvaluationContext::ConstantEvaluated: |
| 15284 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: |
| 15285 | Result = OdrUseContext::Used; |
| 15286 | break; |
| 15287 | |
| 15288 | case Sema::ExpressionEvaluationContext::DiscardedStatement: |
| 15289 | Result = OdrUseContext::FormallyOdrUsed; |
| 15290 | break; |
| 15291 | |
| 15292 | case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
| 15293 | // A default argument formally results in odr-use, but doesn't actually |
| 15294 | // result in a use in any real sense until it itself is used. |
| 15295 | Result = OdrUseContext::FormallyOdrUsed; |
| 15296 | break; |
| 15297 | } |
| 15298 | |
| 15299 | if (SemaRef.CurContext->isDependentContext()) |
| 15300 | return OdrUseContext::Dependent; |
| 15301 | |
| 15302 | return Result; |
| 15303 | } |
| 15304 | |
| 15305 | static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { |
| 15306 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); |
| 15307 | return Func->isConstexpr() && |
| 15308 | (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); |
| 15309 | } |
| 15310 | |
| 15311 | /// Mark a function referenced, and check whether it is odr-used |
| 15312 | /// (C++ [basic.def.odr]p2, C99 6.9p3) |
| 15313 | void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, |
| 15314 | bool MightBeOdrUse) { |
| 15315 | assert(Func && "No function?" ); |
| 15316 | |
| 15317 | Func->setReferenced(); |
| 15318 | |
| 15319 | // Recursive functions aren't really used until they're used from some other |
| 15320 | // context. |
| 15321 | bool IsRecursiveCall = CurContext == Func; |
| 15322 | |
| 15323 | // C++11 [basic.def.odr]p3: |
| 15324 | // A function whose name appears as a potentially-evaluated expression is |
| 15325 | // odr-used if it is the unique lookup result or the selected member of a |
| 15326 | // set of overloaded functions [...]. |
| 15327 | // |
| 15328 | // We (incorrectly) mark overload resolution as an unevaluated context, so we |
| 15329 | // can just check that here. |
| 15330 | OdrUseContext OdrUse = |
| 15331 | MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; |
| 15332 | if (IsRecursiveCall && OdrUse == OdrUseContext::Used) |
| 15333 | OdrUse = OdrUseContext::FormallyOdrUsed; |
| 15334 | |
| 15335 | // C++20 [expr.const]p12: |
| 15336 | // A function [...] is needed for constant evaluation if it is [...] a |
| 15337 | // constexpr function that is named by an expression that is potentially |
| 15338 | // constant evaluated |
| 15339 | bool NeededForConstantEvaluation = |
| 15340 | isPotentiallyConstantEvaluatedContext(*this) && |
| 15341 | isImplicitlyDefinableConstexprFunction(Func); |
| 15342 | |
| 15343 | // Determine whether we require a function definition to exist, per |
| 15344 | // C++11 [temp.inst]p3: |
| 15345 | // Unless a function template specialization has been explicitly |
| 15346 | // instantiated or explicitly specialized, the function template |
| 15347 | // specialization is implicitly instantiated when the specialization is |
| 15348 | // referenced in a context that requires a function definition to exist. |
| 15349 | // C++20 [temp.inst]p7: |
| 15350 | // The existence of a definition of a [...] function is considered to |
| 15351 | // affect the semantics of the program if the [...] function is needed for |
| 15352 | // constant evaluation by an expression |
| 15353 | // C++20 [basic.def.odr]p10: |
| 15354 | // Every program shall contain exactly one definition of every non-inline |
| 15355 | // function or variable that is odr-used in that program outside of a |
| 15356 | // discarded statement |
| 15357 | // C++20 [special]p1: |
| 15358 | // The implementation will implicitly define [defaulted special members] |
| 15359 | // if they are odr-used or needed for constant evaluation. |
| 15360 | // |
| 15361 | // Note that we skip the implicit instantiation of templates that are only |
| 15362 | // used in unused default arguments or by recursive calls to themselves. |
| 15363 | // This is formally non-conforming, but seems reasonable in practice. |
| 15364 | bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || |
| 15365 | NeededForConstantEvaluation); |
| 15366 | |
| 15367 | // C++14 [temp.expl.spec]p6: |
| 15368 | // If a template [...] is explicitly specialized then that specialization |
| 15369 | // shall be declared before the first use of that specialization that would |
| 15370 | // cause an implicit instantiation to take place, in every translation unit |
| 15371 | // in which such a use occurs |
| 15372 | if (NeedDefinition && |
| 15373 | (Func->getTemplateSpecializationKind() != TSK_Undeclared || |
| 15374 | Func->getMemberSpecializationInfo())) |
| 15375 | checkSpecializationVisibility(Loc, Func); |
| 15376 | |
| 15377 | // C++14 [except.spec]p17: |
| 15378 | // An exception-specification is considered to be needed when: |
| 15379 | // - the function is odr-used or, if it appears in an unevaluated operand, |
| 15380 | // would be odr-used if the expression were potentially-evaluated; |
| 15381 | // |
| 15382 | // Note, we do this even if MightBeOdrUse is false. That indicates that the |
| 15383 | // function is a pure virtual function we're calling, and in that case the |
| 15384 | // function was selected by overload resolution and we need to resolve its |
| 15385 | // exception specification for a different reason. |
| 15386 | const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); |
| 15387 | if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) |
| 15388 | ResolveExceptionSpec(Loc, FPT); |
| 15389 | |
| 15390 | if (getLangOpts().CUDA) |
| 15391 | CheckCUDACall(Loc, Func); |
| 15392 | |
| 15393 | // If we need a definition, try to create one. |
| 15394 | if (NeedDefinition && !Func->getBody()) { |
| 15395 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { |
| 15396 | Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); |
| 15397 | if (Constructor->isDefaulted() && !Constructor->isDeleted()) { |
| 15398 | if (Constructor->isDefaultConstructor()) { |
| 15399 | if (Constructor->isTrivial() && |
| 15400 | !Constructor->hasAttr<DLLExportAttr>()) |
| 15401 | return; |
| 15402 | DefineImplicitDefaultConstructor(Loc, Constructor); |
| 15403 | } else if (Constructor->isCopyConstructor()) { |
| 15404 | DefineImplicitCopyConstructor(Loc, Constructor); |
| 15405 | } else if (Constructor->isMoveConstructor()) { |
| 15406 | DefineImplicitMoveConstructor(Loc, Constructor); |
| 15407 | } |
| 15408 | } else if (Constructor->getInheritedConstructor()) { |
| 15409 | DefineInheritingConstructor(Loc, Constructor); |
| 15410 | } |
| 15411 | } else if (CXXDestructorDecl *Destructor = |
| 15412 | dyn_cast<CXXDestructorDecl>(Func)) { |
| 15413 | Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); |
| 15414 | if (Destructor->isDefaulted() && !Destructor->isDeleted()) { |
| 15415 | if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) |
| 15416 | return; |
| 15417 | DefineImplicitDestructor(Loc, Destructor); |
| 15418 | } |
| 15419 | if (Destructor->isVirtual() && getLangOpts().AppleKext) |
| 15420 | MarkVTableUsed(Loc, Destructor->getParent()); |
| 15421 | } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { |
| 15422 | if (MethodDecl->isOverloadedOperator() && |
| 15423 | MethodDecl->getOverloadedOperator() == OO_Equal) { |
| 15424 | MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); |
| 15425 | if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { |
| 15426 | if (MethodDecl->isCopyAssignmentOperator()) |
| 15427 | DefineImplicitCopyAssignment(Loc, MethodDecl); |
| 15428 | else if (MethodDecl->isMoveAssignmentOperator()) |
| 15429 | DefineImplicitMoveAssignment(Loc, MethodDecl); |
| 15430 | } |
| 15431 | } else if (isa<CXXConversionDecl>(MethodDecl) && |
| 15432 | MethodDecl->getParent()->isLambda()) { |
| 15433 | CXXConversionDecl *Conversion = |
| 15434 | cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); |
| 15435 | if (Conversion->isLambdaToBlockPointerConversion()) |
| 15436 | DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); |
| 15437 | else |
| 15438 | DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); |
| 15439 | } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) |
| 15440 | MarkVTableUsed(Loc, MethodDecl->getParent()); |
| 15441 | } |
| 15442 | |
| 15443 | // Implicit instantiation of function templates and member functions of |
| 15444 | // class templates. |
| 15445 | if (Func->isImplicitlyInstantiable()) { |
| 15446 | TemplateSpecializationKind TSK = |
| 15447 | Func->getTemplateSpecializationKindForInstantiation(); |
| 15448 | SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); |
| 15449 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
| 15450 | if (FirstInstantiation) { |
| 15451 | PointOfInstantiation = Loc; |
| 15452 | Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 15453 | } else if (TSK != TSK_ImplicitInstantiation) { |
| 15454 | // Use the point of use as the point of instantiation, instead of the |
| 15455 | // point of explicit instantiation (which we track as the actual point |
| 15456 | // of instantiation). This gives better backtraces in diagnostics. |
| 15457 | PointOfInstantiation = Loc; |
| 15458 | } |
| 15459 | |
| 15460 | if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || |
| 15461 | Func->isConstexpr()) { |
| 15462 | if (isa<CXXRecordDecl>(Func->getDeclContext()) && |
| 15463 | cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && |
| 15464 | CodeSynthesisContexts.size()) |
| 15465 | PendingLocalImplicitInstantiations.push_back( |
| 15466 | std::make_pair(Func, PointOfInstantiation)); |
| 15467 | else if (Func->isConstexpr()) |
| 15468 | // Do not defer instantiations of constexpr functions, to avoid the |
| 15469 | // expression evaluator needing to call back into Sema if it sees a |
| 15470 | // call to such a function. |
| 15471 | InstantiateFunctionDefinition(PointOfInstantiation, Func); |
| 15472 | else { |
| 15473 | Func->setInstantiationIsPending(true); |
| 15474 | PendingInstantiations.push_back( |
| 15475 | std::make_pair(Func, PointOfInstantiation)); |
| 15476 | // Notify the consumer that a function was implicitly instantiated. |
| 15477 | Consumer.HandleCXXImplicitFunctionInstantiation(Func); |
| 15478 | } |
| 15479 | } |
| 15480 | } else { |
| 15481 | // Walk redefinitions, as some of them may be instantiable. |
| 15482 | for (auto i : Func->redecls()) { |
| 15483 | if (!i->isUsed(false) && i->isImplicitlyInstantiable()) |
| 15484 | MarkFunctionReferenced(Loc, i, MightBeOdrUse); |
| 15485 | } |
| 15486 | } |
| 15487 | } |
| 15488 | |
| 15489 | // If this is the first "real" use, act on that. |
| 15490 | if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { |
| 15491 | // Keep track of used but undefined functions. |
| 15492 | if (!Func->isDefined()) { |
| 15493 | if (mightHaveNonExternalLinkage(Func)) |
| 15494 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); |
| 15495 | else if (Func->getMostRecentDecl()->isInlined() && |
| 15496 | !LangOpts.GNUInline && |
| 15497 | !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) |
| 15498 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); |
| 15499 | else if (isExternalWithNoLinkageType(Func)) |
| 15500 | UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); |
| 15501 | } |
| 15502 | |
| 15503 | // Some x86 Windows calling conventions mangle the size of the parameter |
| 15504 | // pack into the name. Computing the size of the parameters requires the |
| 15505 | // parameter types to be complete. Check that now. |
| 15506 | if (funcHasParameterSizeMangling(*this, Func)) |
| 15507 | CheckCompleteParameterTypesForMangler(*this, Func, Loc); |
| 15508 | |
| 15509 | Func->markUsed(Context); |
| 15510 | |
| 15511 | if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) |
| 15512 | checkOpenMPDeviceFunction(Loc, Func); |
| 15513 | } |
| 15514 | } |
| 15515 | |
| 15516 | /// Directly mark a variable odr-used. Given a choice, prefer to use |
| 15517 | /// MarkVariableReferenced since it does additional checks and then |
| 15518 | /// calls MarkVarDeclODRUsed. |
| 15519 | /// If the variable must be captured: |
| 15520 | /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext |
| 15521 | /// - else capture it in the DeclContext that maps to the |
| 15522 | /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. |
| 15523 | static void |
| 15524 | MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, |
| 15525 | const unsigned *const FunctionScopeIndexToStopAt = nullptr) { |
| 15526 | // Keep track of used but undefined variables. |
| 15527 | // FIXME: We shouldn't suppress this warning for static data members. |
| 15528 | if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && |
| 15529 | (!Var->isExternallyVisible() || Var->isInline() || |
| 15530 | SemaRef.isExternalWithNoLinkageType(Var)) && |
| 15531 | !(Var->isStaticDataMember() && Var->hasInit())) { |
| 15532 | SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; |
| 15533 | if (old.isInvalid()) |
| 15534 | old = Loc; |
| 15535 | } |
| 15536 | QualType CaptureType, DeclRefType; |
| 15537 | SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, |
| 15538 | /*EllipsisLoc*/ SourceLocation(), |
| 15539 | /*BuildAndDiagnose*/ true, |
| 15540 | CaptureType, DeclRefType, |
| 15541 | FunctionScopeIndexToStopAt); |
| 15542 | |
| 15543 | Var->markUsed(SemaRef.Context); |
| 15544 | } |
| 15545 | |
| 15546 | void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, |
| 15547 | SourceLocation Loc, |
| 15548 | unsigned CapturingScopeIndex) { |
| 15549 | MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); |
| 15550 | } |
| 15551 | |
| 15552 | static void |
| 15553 | diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, |
| 15554 | ValueDecl *var, DeclContext *DC) { |
| 15555 | DeclContext *VarDC = var->getDeclContext(); |
| 15556 | |
| 15557 | // If the parameter still belongs to the translation unit, then |
| 15558 | // we're actually just using one parameter in the declaration of |
| 15559 | // the next. |
| 15560 | if (isa<ParmVarDecl>(var) && |
| 15561 | isa<TranslationUnitDecl>(VarDC)) |
| 15562 | return; |
| 15563 | |
| 15564 | // For C code, don't diagnose about capture if we're not actually in code |
| 15565 | // right now; it's impossible to write a non-constant expression outside of |
| 15566 | // function context, so we'll get other (more useful) diagnostics later. |
| 15567 | // |
| 15568 | // For C++, things get a bit more nasty... it would be nice to suppress this |
| 15569 | // diagnostic for certain cases like using a local variable in an array bound |
| 15570 | // for a member of a local class, but the correct predicate is not obvious. |
| 15571 | if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) |
| 15572 | return; |
| 15573 | |
| 15574 | unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; |
| 15575 | unsigned ContextKind = 3; // unknown |
| 15576 | if (isa<CXXMethodDecl>(VarDC) && |
| 15577 | cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { |
| 15578 | ContextKind = 2; |
| 15579 | } else if (isa<FunctionDecl>(VarDC)) { |
| 15580 | ContextKind = 0; |
| 15581 | } else if (isa<BlockDecl>(VarDC)) { |
| 15582 | ContextKind = 1; |
| 15583 | } |
| 15584 | |
| 15585 | S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) |
| 15586 | << var << ValueKind << ContextKind << VarDC; |
| 15587 | S.Diag(var->getLocation(), diag::note_entity_declared_at) |
| 15588 | << var; |
| 15589 | |
| 15590 | // FIXME: Add additional diagnostic info about class etc. which prevents |
| 15591 | // capture. |
| 15592 | } |
| 15593 | |
| 15594 | |
| 15595 | static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, |
| 15596 | bool &SubCapturesAreNested, |
| 15597 | QualType &CaptureType, |
| 15598 | QualType &DeclRefType) { |
| 15599 | // Check whether we've already captured it. |
| 15600 | if (CSI->CaptureMap.count(Var)) { |
| 15601 | // If we found a capture, any subcaptures are nested. |
| 15602 | SubCapturesAreNested = true; |
| 15603 | |
| 15604 | // Retrieve the capture type for this variable. |
| 15605 | CaptureType = CSI->getCapture(Var).getCaptureType(); |
| 15606 | |
| 15607 | // Compute the type of an expression that refers to this variable. |
| 15608 | DeclRefType = CaptureType.getNonReferenceType(); |
| 15609 | |
| 15610 | // Similarly to mutable captures in lambda, all the OpenMP captures by copy |
| 15611 | // are mutable in the sense that user can change their value - they are |
| 15612 | // private instances of the captured declarations. |
| 15613 | const Capture &Cap = CSI->getCapture(Var); |
| 15614 | if (Cap.isCopyCapture() && |
| 15615 | !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && |
| 15616 | !(isa<CapturedRegionScopeInfo>(CSI) && |
| 15617 | cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) |
| 15618 | DeclRefType.addConst(); |
| 15619 | return true; |
| 15620 | } |
| 15621 | return false; |
| 15622 | } |
| 15623 | |
| 15624 | // Only block literals, captured statements, and lambda expressions can |
| 15625 | // capture; other scopes don't work. |
| 15626 | static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, |
| 15627 | SourceLocation Loc, |
| 15628 | const bool Diagnose, Sema &S) { |
| 15629 | if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) |
| 15630 | return getLambdaAwareParentOfDeclContext(DC); |
| 15631 | else if (Var->hasLocalStorage()) { |
| 15632 | if (Diagnose) |
| 15633 | diagnoseUncapturableValueReference(S, Loc, Var, DC); |
| 15634 | } |
| 15635 | return nullptr; |
| 15636 | } |
| 15637 | |
| 15638 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
| 15639 | // certain types of variables (unnamed, variably modified types etc.) |
| 15640 | // so check for eligibility. |
| 15641 | static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, |
| 15642 | SourceLocation Loc, |
| 15643 | const bool Diagnose, Sema &S) { |
| 15644 | |
| 15645 | bool IsBlock = isa<BlockScopeInfo>(CSI); |
| 15646 | bool IsLambda = isa<LambdaScopeInfo>(CSI); |
| 15647 | |
| 15648 | // Lambdas are not allowed to capture unnamed variables |
| 15649 | // (e.g. anonymous unions). |
| 15650 | // FIXME: The C++11 rule don't actually state this explicitly, but I'm |
| 15651 | // assuming that's the intent. |
| 15652 | if (IsLambda && !Var->getDeclName()) { |
| 15653 | if (Diagnose) { |
| 15654 | S.Diag(Loc, diag::err_lambda_capture_anonymous_var); |
| 15655 | S.Diag(Var->getLocation(), diag::note_declared_at); |
| 15656 | } |
| 15657 | return false; |
| 15658 | } |
| 15659 | |
| 15660 | // Prohibit variably-modified types in blocks; they're difficult to deal with. |
| 15661 | if (Var->getType()->isVariablyModifiedType() && IsBlock) { |
| 15662 | if (Diagnose) { |
| 15663 | S.Diag(Loc, diag::err_ref_vm_type); |
| 15664 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
| 15665 | << Var->getDeclName(); |
| 15666 | } |
| 15667 | return false; |
| 15668 | } |
| 15669 | // Prohibit structs with flexible array members too. |
| 15670 | // We cannot capture what is in the tail end of the struct. |
| 15671 | if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { |
| 15672 | if (VTTy->getDecl()->hasFlexibleArrayMember()) { |
| 15673 | if (Diagnose) { |
| 15674 | if (IsBlock) |
| 15675 | S.Diag(Loc, diag::err_ref_flexarray_type); |
| 15676 | else |
| 15677 | S.Diag(Loc, diag::err_lambda_capture_flexarray_type) |
| 15678 | << Var->getDeclName(); |
| 15679 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
| 15680 | << Var->getDeclName(); |
| 15681 | } |
| 15682 | return false; |
| 15683 | } |
| 15684 | } |
| 15685 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
| 15686 | // Lambdas and captured statements are not allowed to capture __block |
| 15687 | // variables; they don't support the expected semantics. |
| 15688 | if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { |
| 15689 | if (Diagnose) { |
| 15690 | S.Diag(Loc, diag::err_capture_block_variable) |
| 15691 | << Var->getDeclName() << !IsLambda; |
| 15692 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
| 15693 | << Var->getDeclName(); |
| 15694 | } |
| 15695 | return false; |
| 15696 | } |
| 15697 | // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks |
| 15698 | if (S.getLangOpts().OpenCL && IsBlock && |
| 15699 | Var->getType()->isBlockPointerType()) { |
| 15700 | if (Diagnose) |
| 15701 | S.Diag(Loc, diag::err_opencl_block_ref_block); |
| 15702 | return false; |
| 15703 | } |
| 15704 | |
| 15705 | return true; |
| 15706 | } |
| 15707 | |
| 15708 | // Returns true if the capture by block was successful. |
| 15709 | static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, |
| 15710 | SourceLocation Loc, |
| 15711 | const bool BuildAndDiagnose, |
| 15712 | QualType &CaptureType, |
| 15713 | QualType &DeclRefType, |
| 15714 | const bool Nested, |
| 15715 | Sema &S, bool Invalid) { |
| 15716 | bool ByRef = false; |
| 15717 | |
| 15718 | // Blocks are not allowed to capture arrays, excepting OpenCL. |
| 15719 | // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference |
| 15720 | // (decayed to pointers). |
| 15721 | if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { |
| 15722 | if (BuildAndDiagnose) { |
| 15723 | S.Diag(Loc, diag::err_ref_array_type); |
| 15724 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
| 15725 | << Var->getDeclName(); |
| 15726 | Invalid = true; |
| 15727 | } else { |
| 15728 | return false; |
| 15729 | } |
| 15730 | } |
| 15731 | |
| 15732 | // Forbid the block-capture of autoreleasing variables. |
| 15733 | if (!Invalid && |
| 15734 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
| 15735 | if (BuildAndDiagnose) { |
| 15736 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) |
| 15737 | << /*block*/ 0; |
| 15738 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
| 15739 | << Var->getDeclName(); |
| 15740 | Invalid = true; |
| 15741 | } else { |
| 15742 | return false; |
| 15743 | } |
| 15744 | } |
| 15745 | |
| 15746 | // Warn about implicitly autoreleasing indirect parameters captured by blocks. |
| 15747 | if (const auto *PT = CaptureType->getAs<PointerType>()) { |
| 15748 | // This function finds out whether there is an AttributedType of kind |
| 15749 | // attr::ObjCOwnership in Ty. The existence of AttributedType of kind |
| 15750 | // attr::ObjCOwnership implies __autoreleasing was explicitly specified |
| 15751 | // rather than being added implicitly by the compiler. |
| 15752 | auto IsObjCOwnershipAttributedType = [](QualType Ty) { |
| 15753 | while (const auto *AttrTy = Ty->getAs<AttributedType>()) { |
| 15754 | if (AttrTy->getAttrKind() == attr::ObjCOwnership) |
| 15755 | return true; |
| 15756 | |
| 15757 | // Peel off AttributedTypes that are not of kind ObjCOwnership. |
| 15758 | Ty = AttrTy->getModifiedType(); |
| 15759 | } |
| 15760 | |
| 15761 | return false; |
| 15762 | }; |
| 15763 | |
| 15764 | QualType PointeeTy = PT->getPointeeType(); |
| 15765 | |
| 15766 | if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && |
| 15767 | PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && |
| 15768 | !IsObjCOwnershipAttributedType(PointeeTy)) { |
| 15769 | if (BuildAndDiagnose) { |
| 15770 | SourceLocation VarLoc = Var->getLocation(); |
| 15771 | S.Diag(Loc, diag::warn_block_capture_autoreleasing); |
| 15772 | S.Diag(VarLoc, diag::note_declare_parameter_strong); |
| 15773 | } |
| 15774 | } |
| 15775 | } |
| 15776 | |
| 15777 | const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); |
| 15778 | if (HasBlocksAttr || CaptureType->isReferenceType() || |
| 15779 | (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { |
| 15780 | // Block capture by reference does not change the capture or |
| 15781 | // declaration reference types. |
| 15782 | ByRef = true; |
| 15783 | } else { |
| 15784 | // Block capture by copy introduces 'const'. |
| 15785 | CaptureType = CaptureType.getNonReferenceType().withConst(); |
| 15786 | DeclRefType = CaptureType; |
| 15787 | } |
| 15788 | |
| 15789 | // Actually capture the variable. |
| 15790 | if (BuildAndDiagnose) |
| 15791 | BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), |
| 15792 | CaptureType, Invalid); |
| 15793 | |
| 15794 | return !Invalid; |
| 15795 | } |
| 15796 | |
| 15797 | |
| 15798 | /// Capture the given variable in the captured region. |
| 15799 | static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, |
| 15800 | VarDecl *Var, |
| 15801 | SourceLocation Loc, |
| 15802 | const bool BuildAndDiagnose, |
| 15803 | QualType &CaptureType, |
| 15804 | QualType &DeclRefType, |
| 15805 | const bool RefersToCapturedVariable, |
| 15806 | Sema &S, bool Invalid) { |
| 15807 | // By default, capture variables by reference. |
| 15808 | bool ByRef = true; |
| 15809 | // Using an LValue reference type is consistent with Lambdas (see below). |
| 15810 | if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { |
| 15811 | if (S.isOpenMPCapturedDecl(Var)) { |
| 15812 | bool HasConst = DeclRefType.isConstQualified(); |
| 15813 | DeclRefType = DeclRefType.getUnqualifiedType(); |
| 15814 | // Don't lose diagnostics about assignments to const. |
| 15815 | if (HasConst) |
| 15816 | DeclRefType.addConst(); |
| 15817 | } |
| 15818 | ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); |
| 15819 | } |
| 15820 | |
| 15821 | if (ByRef) |
| 15822 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); |
| 15823 | else |
| 15824 | CaptureType = DeclRefType; |
| 15825 | |
| 15826 | // Actually capture the variable. |
| 15827 | if (BuildAndDiagnose) |
| 15828 | RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, |
| 15829 | Loc, SourceLocation(), CaptureType, Invalid); |
| 15830 | |
| 15831 | return !Invalid; |
| 15832 | } |
| 15833 | |
| 15834 | /// Capture the given variable in the lambda. |
| 15835 | static bool captureInLambda(LambdaScopeInfo *LSI, |
| 15836 | VarDecl *Var, |
| 15837 | SourceLocation Loc, |
| 15838 | const bool BuildAndDiagnose, |
| 15839 | QualType &CaptureType, |
| 15840 | QualType &DeclRefType, |
| 15841 | const bool RefersToCapturedVariable, |
| 15842 | const Sema::TryCaptureKind Kind, |
| 15843 | SourceLocation EllipsisLoc, |
| 15844 | const bool IsTopScope, |
| 15845 | Sema &S, bool Invalid) { |
| 15846 | // Determine whether we are capturing by reference or by value. |
| 15847 | bool ByRef = false; |
| 15848 | if (IsTopScope && Kind != Sema::TryCapture_Implicit) { |
| 15849 | ByRef = (Kind == Sema::TryCapture_ExplicitByRef); |
| 15850 | } else { |
| 15851 | ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); |
| 15852 | } |
| 15853 | |
| 15854 | // Compute the type of the field that will capture this variable. |
| 15855 | if (ByRef) { |
| 15856 | // C++11 [expr.prim.lambda]p15: |
| 15857 | // An entity is captured by reference if it is implicitly or |
| 15858 | // explicitly captured but not captured by copy. It is |
| 15859 | // unspecified whether additional unnamed non-static data |
| 15860 | // members are declared in the closure type for entities |
| 15861 | // captured by reference. |
| 15862 | // |
| 15863 | // FIXME: It is not clear whether we want to build an lvalue reference |
| 15864 | // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears |
| 15865 | // to do the former, while EDG does the latter. Core issue 1249 will |
| 15866 | // clarify, but for now we follow GCC because it's a more permissive and |
| 15867 | // easily defensible position. |
| 15868 | CaptureType = S.Context.getLValueReferenceType(DeclRefType); |
| 15869 | } else { |
| 15870 | // C++11 [expr.prim.lambda]p14: |
| 15871 | // For each entity captured by copy, an unnamed non-static |
| 15872 | // data member is declared in the closure type. The |
| 15873 | // declaration order of these members is unspecified. The type |
| 15874 | // of such a data member is the type of the corresponding |
| 15875 | // captured entity if the entity is not a reference to an |
| 15876 | // object, or the referenced type otherwise. [Note: If the |
| 15877 | // captured entity is a reference to a function, the |
| 15878 | // corresponding data member is also a reference to a |
| 15879 | // function. - end note ] |
| 15880 | if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ |
| 15881 | if (!RefType->getPointeeType()->isFunctionType()) |
| 15882 | CaptureType = RefType->getPointeeType(); |
| 15883 | } |
| 15884 | |
| 15885 | // Forbid the lambda copy-capture of autoreleasing variables. |
| 15886 | if (!Invalid && |
| 15887 | CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { |
| 15888 | if (BuildAndDiagnose) { |
| 15889 | S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; |
| 15890 | S.Diag(Var->getLocation(), diag::note_previous_decl) |
| 15891 | << Var->getDeclName(); |
| 15892 | Invalid = true; |
| 15893 | } else { |
| 15894 | return false; |
| 15895 | } |
| 15896 | } |
| 15897 | |
| 15898 | // Make sure that by-copy captures are of a complete and non-abstract type. |
| 15899 | if (!Invalid && BuildAndDiagnose) { |
| 15900 | if (!CaptureType->isDependentType() && |
| 15901 | S.RequireCompleteType(Loc, CaptureType, |
| 15902 | diag::err_capture_of_incomplete_type, |
| 15903 | Var->getDeclName())) |
| 15904 | Invalid = true; |
| 15905 | else if (S.RequireNonAbstractType(Loc, CaptureType, |
| 15906 | diag::err_capture_of_abstract_type)) |
| 15907 | Invalid = true; |
| 15908 | } |
| 15909 | } |
| 15910 | |
| 15911 | // Compute the type of a reference to this captured variable. |
| 15912 | if (ByRef) |
| 15913 | DeclRefType = CaptureType.getNonReferenceType(); |
| 15914 | else { |
| 15915 | // C++ [expr.prim.lambda]p5: |
| 15916 | // The closure type for a lambda-expression has a public inline |
| 15917 | // function call operator [...]. This function call operator is |
| 15918 | // declared const (9.3.1) if and only if the lambda-expression's |
| 15919 | // parameter-declaration-clause is not followed by mutable. |
| 15920 | DeclRefType = CaptureType.getNonReferenceType(); |
| 15921 | if (!LSI->Mutable && !CaptureType->isReferenceType()) |
| 15922 | DeclRefType.addConst(); |
| 15923 | } |
| 15924 | |
| 15925 | // Add the capture. |
| 15926 | if (BuildAndDiagnose) |
| 15927 | LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, |
| 15928 | Loc, EllipsisLoc, CaptureType, Invalid); |
| 15929 | |
| 15930 | return !Invalid; |
| 15931 | } |
| 15932 | |
| 15933 | bool Sema::tryCaptureVariable( |
| 15934 | VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, |
| 15935 | SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, |
| 15936 | QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { |
| 15937 | // An init-capture is notionally from the context surrounding its |
| 15938 | // declaration, but its parent DC is the lambda class. |
| 15939 | DeclContext *VarDC = Var->getDeclContext(); |
| 15940 | if (Var->isInitCapture()) |
| 15941 | VarDC = VarDC->getParent(); |
| 15942 | |
| 15943 | DeclContext *DC = CurContext; |
| 15944 | const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
| 15945 | ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; |
| 15946 | // We need to sync up the Declaration Context with the |
| 15947 | // FunctionScopeIndexToStopAt |
| 15948 | if (FunctionScopeIndexToStopAt) { |
| 15949 | unsigned FSIndex = FunctionScopes.size() - 1; |
| 15950 | while (FSIndex != MaxFunctionScopesIndex) { |
| 15951 | DC = getLambdaAwareParentOfDeclContext(DC); |
| 15952 | --FSIndex; |
| 15953 | } |
| 15954 | } |
| 15955 | |
| 15956 | |
| 15957 | // If the variable is declared in the current context, there is no need to |
| 15958 | // capture it. |
| 15959 | if (VarDC == DC) return true; |
| 15960 | |
| 15961 | // Capture global variables if it is required to use private copy of this |
| 15962 | // variable. |
| 15963 | bool IsGlobal = !Var->hasLocalStorage(); |
| 15964 | if (IsGlobal && |
| 15965 | !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, |
| 15966 | MaxFunctionScopesIndex))) |
| 15967 | return true; |
| 15968 | Var = Var->getCanonicalDecl(); |
| 15969 | |
| 15970 | // Walk up the stack to determine whether we can capture the variable, |
| 15971 | // performing the "simple" checks that don't depend on type. We stop when |
| 15972 | // we've either hit the declared scope of the variable or find an existing |
| 15973 | // capture of that variable. We start from the innermost capturing-entity |
| 15974 | // (the DC) and ensure that all intervening capturing-entities |
| 15975 | // (blocks/lambdas etc.) between the innermost capturer and the variable`s |
| 15976 | // declcontext can either capture the variable or have already captured |
| 15977 | // the variable. |
| 15978 | CaptureType = Var->getType(); |
| 15979 | DeclRefType = CaptureType.getNonReferenceType(); |
| 15980 | bool Nested = false; |
| 15981 | bool Explicit = (Kind != TryCapture_Implicit); |
| 15982 | unsigned FunctionScopesIndex = MaxFunctionScopesIndex; |
| 15983 | do { |
| 15984 | // Only block literals, captured statements, and lambda expressions can |
| 15985 | // capture; other scopes don't work. |
| 15986 | DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, |
| 15987 | ExprLoc, |
| 15988 | BuildAndDiagnose, |
| 15989 | *this); |
| 15990 | // We need to check for the parent *first* because, if we *have* |
| 15991 | // private-captured a global variable, we need to recursively capture it in |
| 15992 | // intermediate blocks, lambdas, etc. |
| 15993 | if (!ParentDC) { |
| 15994 | if (IsGlobal) { |
| 15995 | FunctionScopesIndex = MaxFunctionScopesIndex - 1; |
| 15996 | break; |
| 15997 | } |
| 15998 | return true; |
| 15999 | } |
| 16000 | |
| 16001 | FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; |
| 16002 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); |
| 16003 | |
| 16004 | |
| 16005 | // Check whether we've already captured it. |
| 16006 | if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, |
| 16007 | DeclRefType)) { |
| 16008 | CSI->getCapture(Var).markUsed(BuildAndDiagnose); |
| 16009 | break; |
| 16010 | } |
| 16011 | // If we are instantiating a generic lambda call operator body, |
| 16012 | // we do not want to capture new variables. What was captured |
| 16013 | // during either a lambdas transformation or initial parsing |
| 16014 | // should be used. |
| 16015 | if (isGenericLambdaCallOperatorSpecialization(DC)) { |
| 16016 | if (BuildAndDiagnose) { |
| 16017 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); |
| 16018 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { |
| 16019 | Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); |
| 16020 | Diag(Var->getLocation(), diag::note_previous_decl) |
| 16021 | << Var->getDeclName(); |
| 16022 | Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); |
| 16023 | } else |
| 16024 | diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); |
| 16025 | } |
| 16026 | return true; |
| 16027 | } |
| 16028 | |
| 16029 | // Try to capture variable-length arrays types. |
| 16030 | if (Var->getType()->isVariablyModifiedType()) { |
| 16031 | // We're going to walk down into the type and look for VLA |
| 16032 | // expressions. |
| 16033 | QualType QTy = Var->getType(); |
| 16034 | if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) |
| 16035 | QTy = PVD->getOriginalType(); |
| 16036 | captureVariablyModifiedType(Context, QTy, CSI); |
| 16037 | } |
| 16038 | |
| 16039 | if (getLangOpts().OpenMP) { |
| 16040 | if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { |
| 16041 | // OpenMP private variables should not be captured in outer scope, so |
| 16042 | // just break here. Similarly, global variables that are captured in a |
| 16043 | // target region should not be captured outside the scope of the region. |
| 16044 | if (RSI->CapRegionKind == CR_OpenMP) { |
| 16045 | bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); |
| 16046 | auto IsTargetCap = !IsOpenMPPrivateDecl && |
| 16047 | isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); |
| 16048 | // When we detect target captures we are looking from inside the |
| 16049 | // target region, therefore we need to propagate the capture from the |
| 16050 | // enclosing region. Therefore, the capture is not initially nested. |
| 16051 | if (IsTargetCap) |
| 16052 | adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); |
| 16053 | |
| 16054 | if (IsTargetCap || IsOpenMPPrivateDecl) { |
| 16055 | Nested = !IsTargetCap; |
| 16056 | DeclRefType = DeclRefType.getUnqualifiedType(); |
| 16057 | CaptureType = Context.getLValueReferenceType(DeclRefType); |
| 16058 | break; |
| 16059 | } |
| 16060 | } |
| 16061 | } |
| 16062 | } |
| 16063 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { |
| 16064 | // No capture-default, and this is not an explicit capture |
| 16065 | // so cannot capture this variable. |
| 16066 | if (BuildAndDiagnose) { |
| 16067 | Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); |
| 16068 | Diag(Var->getLocation(), diag::note_previous_decl) |
| 16069 | << Var->getDeclName(); |
| 16070 | if (cast<LambdaScopeInfo>(CSI)->Lambda) |
| 16071 | Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), |
| 16072 | diag::note_lambda_decl); |
| 16073 | // FIXME: If we error out because an outer lambda can not implicitly |
| 16074 | // capture a variable that an inner lambda explicitly captures, we |
| 16075 | // should have the inner lambda do the explicit capture - because |
| 16076 | // it makes for cleaner diagnostics later. This would purely be done |
| 16077 | // so that the diagnostic does not misleadingly claim that a variable |
| 16078 | // can not be captured by a lambda implicitly even though it is captured |
| 16079 | // explicitly. Suggestion: |
| 16080 | // - create const bool VariableCaptureWasInitiallyExplicit = Explicit |
| 16081 | // at the function head |
| 16082 | // - cache the StartingDeclContext - this must be a lambda |
| 16083 | // - captureInLambda in the innermost lambda the variable. |
| 16084 | } |
| 16085 | return true; |
| 16086 | } |
| 16087 | |
| 16088 | FunctionScopesIndex--; |
| 16089 | DC = ParentDC; |
| 16090 | Explicit = false; |
| 16091 | } while (!VarDC->Equals(DC)); |
| 16092 | |
| 16093 | // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) |
| 16094 | // computing the type of the capture at each step, checking type-specific |
| 16095 | // requirements, and adding captures if requested. |
| 16096 | // If the variable had already been captured previously, we start capturing |
| 16097 | // at the lambda nested within that one. |
| 16098 | bool Invalid = false; |
| 16099 | for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; |
| 16100 | ++I) { |
| 16101 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); |
| 16102 | |
| 16103 | // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture |
| 16104 | // certain types of variables (unnamed, variably modified types etc.) |
| 16105 | // so check for eligibility. |
| 16106 | if (!Invalid) |
| 16107 | Invalid = |
| 16108 | !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); |
| 16109 | |
| 16110 | // After encountering an error, if we're actually supposed to capture, keep |
| 16111 | // capturing in nested contexts to suppress any follow-on diagnostics. |
| 16112 | if (Invalid && !BuildAndDiagnose) |
| 16113 | return true; |
| 16114 | |
| 16115 | if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { |
| 16116 | Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, |
| 16117 | DeclRefType, Nested, *this, Invalid); |
| 16118 | Nested = true; |
| 16119 | } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { |
| 16120 | Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, |
| 16121 | CaptureType, DeclRefType, Nested, |
| 16122 | *this, Invalid); |
| 16123 | Nested = true; |
| 16124 | } else { |
| 16125 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); |
| 16126 | Invalid = |
| 16127 | !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, |
| 16128 | DeclRefType, Nested, Kind, EllipsisLoc, |
| 16129 | /*IsTopScope*/ I == N - 1, *this, Invalid); |
| 16130 | Nested = true; |
| 16131 | } |
| 16132 | |
| 16133 | if (Invalid && !BuildAndDiagnose) |
| 16134 | return true; |
| 16135 | } |
| 16136 | return Invalid; |
| 16137 | } |
| 16138 | |
| 16139 | bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, |
| 16140 | TryCaptureKind Kind, SourceLocation EllipsisLoc) { |
| 16141 | QualType CaptureType; |
| 16142 | QualType DeclRefType; |
| 16143 | return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, |
| 16144 | /*BuildAndDiagnose=*/true, CaptureType, |
| 16145 | DeclRefType, nullptr); |
| 16146 | } |
| 16147 | |
| 16148 | bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { |
| 16149 | QualType CaptureType; |
| 16150 | QualType DeclRefType; |
| 16151 | return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), |
| 16152 | /*BuildAndDiagnose=*/false, CaptureType, |
| 16153 | DeclRefType, nullptr); |
| 16154 | } |
| 16155 | |
| 16156 | QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { |
| 16157 | QualType CaptureType; |
| 16158 | QualType DeclRefType; |
| 16159 | |
| 16160 | // Determine whether we can capture this variable. |
| 16161 | if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), |
| 16162 | /*BuildAndDiagnose=*/false, CaptureType, |
| 16163 | DeclRefType, nullptr)) |
| 16164 | return QualType(); |
| 16165 | |
| 16166 | return DeclRefType; |
| 16167 | } |
| 16168 | |
| 16169 | /// Walk the set of potential results of an expression and mark them all as |
| 16170 | /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. |
| 16171 | /// |
| 16172 | /// \return A new expression if we found any potential results, ExprEmpty() if |
| 16173 | /// not, and ExprError() if we diagnosed an error. |
| 16174 | static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, |
| 16175 | NonOdrUseReason NOUR) { |
| 16176 | // Per C++11 [basic.def.odr], a variable is odr-used "unless it is |
| 16177 | // an object that satisfies the requirements for appearing in a |
| 16178 | // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) |
| 16179 | // is immediately applied." This function handles the lvalue-to-rvalue |
| 16180 | // conversion part. |
| 16181 | // |
| 16182 | // If we encounter a node that claims to be an odr-use but shouldn't be, we |
| 16183 | // transform it into the relevant kind of non-odr-use node and rebuild the |
| 16184 | // tree of nodes leading to it. |
| 16185 | // |
| 16186 | // This is a mini-TreeTransform that only transforms a restricted subset of |
| 16187 | // nodes (and only certain operands of them). |
| 16188 | |
| 16189 | // Rebuild a subexpression. |
| 16190 | auto Rebuild = [&](Expr *Sub) { |
| 16191 | return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); |
| 16192 | }; |
| 16193 | |
| 16194 | // Check whether a potential result satisfies the requirements of NOUR. |
| 16195 | auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { |
| 16196 | // Any entity other than a VarDecl is always odr-used whenever it's named |
| 16197 | // in a potentially-evaluated expression. |
| 16198 | auto *VD = dyn_cast<VarDecl>(D); |
| 16199 | if (!VD) |
| 16200 | return true; |
| 16201 | |
| 16202 | // C++2a [basic.def.odr]p4: |
| 16203 | // A variable x whose name appears as a potentially-evalauted expression |
| 16204 | // e is odr-used by e unless |
| 16205 | // -- x is a reference that is usable in constant expressions, or |
| 16206 | // -- x is a variable of non-reference type that is usable in constant |
| 16207 | // expressions and has no mutable subobjects, and e is an element of |
| 16208 | // the set of potential results of an expression of |
| 16209 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
| 16210 | // conversion is applied, or |
| 16211 | // -- x is a variable of non-reference type, and e is an element of the |
| 16212 | // set of potential results of a discarded-value expression to which |
| 16213 | // the lvalue-to-rvalue conversion is not applied |
| 16214 | // |
| 16215 | // We check the first bullet and the "potentially-evaluated" condition in |
| 16216 | // BuildDeclRefExpr. We check the type requirements in the second bullet |
| 16217 | // in CheckLValueToRValueConversionOperand below. |
| 16218 | switch (NOUR) { |
| 16219 | case NOUR_None: |
| 16220 | case NOUR_Unevaluated: |
| 16221 | llvm_unreachable("unexpected non-odr-use-reason" ); |
| 16222 | |
| 16223 | case NOUR_Constant: |
| 16224 | // Constant references were handled when they were built. |
| 16225 | if (VD->getType()->isReferenceType()) |
| 16226 | return true; |
| 16227 | if (auto *RD = VD->getType()->getAsCXXRecordDecl()) |
| 16228 | if (RD->hasMutableFields()) |
| 16229 | return true; |
| 16230 | if (!VD->isUsableInConstantExpressions(S.Context)) |
| 16231 | return true; |
| 16232 | break; |
| 16233 | |
| 16234 | case NOUR_Discarded: |
| 16235 | if (VD->getType()->isReferenceType()) |
| 16236 | return true; |
| 16237 | break; |
| 16238 | } |
| 16239 | return false; |
| 16240 | }; |
| 16241 | |
| 16242 | // Mark that this expression does not constitute an odr-use. |
| 16243 | auto MarkNotOdrUsed = [&] { |
| 16244 | S.MaybeODRUseExprs.erase(E); |
| 16245 | if (LambdaScopeInfo *LSI = S.getCurLambda()) |
| 16246 | LSI->markVariableExprAsNonODRUsed(E); |
| 16247 | }; |
| 16248 | |
| 16249 | // C++2a [basic.def.odr]p2: |
| 16250 | // The set of potential results of an expression e is defined as follows: |
| 16251 | switch (E->getStmtClass()) { |
| 16252 | // -- If e is an id-expression, ... |
| 16253 | case Expr::DeclRefExprClass: { |
| 16254 | auto *DRE = cast<DeclRefExpr>(E); |
| 16255 | if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) |
| 16256 | break; |
| 16257 | |
| 16258 | // Rebuild as a non-odr-use DeclRefExpr. |
| 16259 | MarkNotOdrUsed(); |
| 16260 | TemplateArgumentListInfo TemplateArgStorage, *TemplateArgs = nullptr; |
| 16261 | if (DRE->hasExplicitTemplateArgs()) { |
| 16262 | DRE->copyTemplateArgumentsInto(TemplateArgStorage); |
| 16263 | TemplateArgs = &TemplateArgStorage; |
| 16264 | } |
| 16265 | return DeclRefExpr::Create( |
| 16266 | S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), |
| 16267 | DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), |
| 16268 | DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), |
| 16269 | DRE->getFoundDecl(), TemplateArgs, NOUR); |
| 16270 | } |
| 16271 | |
| 16272 | case Expr::FunctionParmPackExprClass: { |
| 16273 | auto *FPPE = cast<FunctionParmPackExpr>(E); |
| 16274 | // If any of the declarations in the pack is odr-used, then the expression |
| 16275 | // as a whole constitutes an odr-use. |
| 16276 | for (VarDecl *D : *FPPE) |
| 16277 | if (IsPotentialResultOdrUsed(D)) |
| 16278 | return ExprEmpty(); |
| 16279 | |
| 16280 | // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, |
| 16281 | // nothing cares about whether we marked this as an odr-use, but it might |
| 16282 | // be useful for non-compiler tools. |
| 16283 | MarkNotOdrUsed(); |
| 16284 | break; |
| 16285 | } |
| 16286 | |
| 16287 | // FIXME: Implement these. |
| 16288 | // -- If e is a subscripting operation with an array operand... |
| 16289 | // -- If e is a class member access expression [...] naming a non-static |
| 16290 | // data member... |
| 16291 | |
| 16292 | // -- If e is a class member access expression naming a static data member, |
| 16293 | // ... |
| 16294 | case Expr::MemberExprClass: { |
| 16295 | auto *ME = cast<MemberExpr>(E); |
| 16296 | if (ME->getMemberDecl()->isCXXInstanceMember()) |
| 16297 | // FIXME: Recurse to the left-hand side. |
| 16298 | break; |
| 16299 | |
| 16300 | if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) |
| 16301 | break; |
| 16302 | |
| 16303 | // Rebuild as a non-odr-use MemberExpr. |
| 16304 | MarkNotOdrUsed(); |
| 16305 | TemplateArgumentListInfo TemplateArgStorage, *TemplateArgs = nullptr; |
| 16306 | if (ME->hasExplicitTemplateArgs()) { |
| 16307 | ME->copyTemplateArgumentsInto(TemplateArgStorage); |
| 16308 | TemplateArgs = &TemplateArgStorage; |
| 16309 | } |
| 16310 | return MemberExpr::Create( |
| 16311 | S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), |
| 16312 | ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), |
| 16313 | ME->getFoundDecl(), ME->getMemberNameInfo(), TemplateArgs, |
| 16314 | ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); |
| 16315 | return ExprEmpty(); |
| 16316 | } |
| 16317 | |
| 16318 | // FIXME: Implement this. |
| 16319 | // -- If e is a pointer-to-member expression of the form e1 .* e2 ... |
| 16320 | |
| 16321 | // -- If e has the form (e1)... |
| 16322 | case Expr::ParenExprClass: { |
| 16323 | auto *PE = dyn_cast<ParenExpr>(E); |
| 16324 | ExprResult Sub = Rebuild(PE->getSubExpr()); |
| 16325 | if (!Sub.isUsable()) |
| 16326 | return Sub; |
| 16327 | return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); |
| 16328 | } |
| 16329 | |
| 16330 | // FIXME: Implement these. |
| 16331 | // -- If e is a glvalue conditional expression, ... |
| 16332 | // -- If e is a comma expression, ... |
| 16333 | |
| 16334 | // [Clang extension] |
| 16335 | // -- If e has the form __extension__ e1... |
| 16336 | case Expr::UnaryOperatorClass: { |
| 16337 | auto *UO = cast<UnaryOperator>(E); |
| 16338 | if (UO->getOpcode() != UO_Extension) |
| 16339 | break; |
| 16340 | ExprResult Sub = Rebuild(UO->getSubExpr()); |
| 16341 | if (!Sub.isUsable()) |
| 16342 | return Sub; |
| 16343 | return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, |
| 16344 | Sub.get()); |
| 16345 | } |
| 16346 | |
| 16347 | // [Clang extension] |
| 16348 | // -- If e has the form _Generic(...), the set of potential results is the |
| 16349 | // union of the sets of potential results of the associated expressions. |
| 16350 | case Expr::GenericSelectionExprClass: { |
| 16351 | auto *GSE = dyn_cast<GenericSelectionExpr>(E); |
| 16352 | |
| 16353 | SmallVector<Expr *, 4> AssocExprs; |
| 16354 | bool AnyChanged = false; |
| 16355 | for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { |
| 16356 | ExprResult AssocExpr = Rebuild(OrigAssocExpr); |
| 16357 | if (AssocExpr.isInvalid()) |
| 16358 | return ExprError(); |
| 16359 | if (AssocExpr.isUsable()) { |
| 16360 | AssocExprs.push_back(AssocExpr.get()); |
| 16361 | AnyChanged = true; |
| 16362 | } else { |
| 16363 | AssocExprs.push_back(OrigAssocExpr); |
| 16364 | } |
| 16365 | } |
| 16366 | |
| 16367 | return AnyChanged ? S.CreateGenericSelectionExpr( |
| 16368 | GSE->getGenericLoc(), GSE->getDefaultLoc(), |
| 16369 | GSE->getRParenLoc(), GSE->getControllingExpr(), |
| 16370 | GSE->getAssocTypeSourceInfos(), AssocExprs) |
| 16371 | : ExprEmpty(); |
| 16372 | } |
| 16373 | |
| 16374 | // [Clang extension] |
| 16375 | // -- If e has the form __builtin_choose_expr(...), the set of potential |
| 16376 | // results is the union of the sets of potential results of the |
| 16377 | // second and third subexpressions. |
| 16378 | case Expr::ChooseExprClass: { |
| 16379 | auto *CE = dyn_cast<ChooseExpr>(E); |
| 16380 | |
| 16381 | ExprResult LHS = Rebuild(CE->getLHS()); |
| 16382 | if (LHS.isInvalid()) |
| 16383 | return ExprError(); |
| 16384 | |
| 16385 | ExprResult RHS = Rebuild(CE->getLHS()); |
| 16386 | if (RHS.isInvalid()) |
| 16387 | return ExprError(); |
| 16388 | |
| 16389 | if (!LHS.get() && !RHS.get()) |
| 16390 | return ExprEmpty(); |
| 16391 | if (!LHS.isUsable()) |
| 16392 | LHS = CE->getLHS(); |
| 16393 | if (!RHS.isUsable()) |
| 16394 | RHS = CE->getRHS(); |
| 16395 | |
| 16396 | return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), |
| 16397 | RHS.get(), CE->getRParenLoc()); |
| 16398 | } |
| 16399 | |
| 16400 | // Step through non-syntactic nodes. |
| 16401 | case Expr::ConstantExprClass: { |
| 16402 | auto *CE = dyn_cast<ConstantExpr>(E); |
| 16403 | ExprResult Sub = Rebuild(CE->getSubExpr()); |
| 16404 | if (!Sub.isUsable()) |
| 16405 | return Sub; |
| 16406 | return ConstantExpr::Create(S.Context, Sub.get()); |
| 16407 | } |
| 16408 | |
| 16409 | default: |
| 16410 | break; |
| 16411 | } |
| 16412 | |
| 16413 | // Can't traverse through this node. Nothing to do. |
| 16414 | return ExprEmpty(); |
| 16415 | } |
| 16416 | |
| 16417 | ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { |
| 16418 | // C++2a [basic.def.odr]p4: |
| 16419 | // [...] an expression of non-volatile-qualified non-class type to which |
| 16420 | // the lvalue-to-rvalue conversion is applied [...] |
| 16421 | if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) |
| 16422 | return E; |
| 16423 | |
| 16424 | ExprResult Result = |
| 16425 | rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); |
| 16426 | if (Result.isInvalid()) |
| 16427 | return ExprError(); |
| 16428 | return Result.get() ? Result : E; |
| 16429 | } |
| 16430 | |
| 16431 | ExprResult Sema::ActOnConstantExpression(ExprResult Res) { |
| 16432 | Res = CorrectDelayedTyposInExpr(Res); |
| 16433 | |
| 16434 | if (!Res.isUsable()) |
| 16435 | return Res; |
| 16436 | |
| 16437 | // If a constant-expression is a reference to a variable where we delay |
| 16438 | // deciding whether it is an odr-use, just assume we will apply the |
| 16439 | // lvalue-to-rvalue conversion. In the one case where this doesn't happen |
| 16440 | // (a non-type template argument), we have special handling anyway. |
| 16441 | return CheckLValueToRValueConversionOperand(Res.get()); |
| 16442 | } |
| 16443 | |
| 16444 | void Sema::CleanupVarDeclMarking() { |
| 16445 | // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive |
| 16446 | // call. |
| 16447 | MaybeODRUseExprSet LocalMaybeODRUseExprs; |
| 16448 | std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); |
| 16449 | |
| 16450 | for (Expr *E : LocalMaybeODRUseExprs) { |
| 16451 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { |
| 16452 | MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), |
| 16453 | DRE->getLocation(), *this); |
| 16454 | } else if (auto *ME = dyn_cast<MemberExpr>(E)) { |
| 16455 | MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), |
| 16456 | *this); |
| 16457 | } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { |
| 16458 | for (VarDecl *VD : *FP) |
| 16459 | MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); |
| 16460 | } else { |
| 16461 | llvm_unreachable("Unexpected expression" ); |
| 16462 | } |
| 16463 | } |
| 16464 | |
| 16465 | assert(MaybeODRUseExprs.empty() && |
| 16466 | "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?" ); |
| 16467 | } |
| 16468 | |
| 16469 | static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, |
| 16470 | VarDecl *Var, Expr *E) { |
| 16471 | assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || |
| 16472 | isa<FunctionParmPackExpr>(E)) && |
| 16473 | "Invalid Expr argument to DoMarkVarDeclReferenced" ); |
| 16474 | Var->setReferenced(); |
| 16475 | |
| 16476 | if (Var->isInvalidDecl()) |
| 16477 | return; |
| 16478 | |
| 16479 | auto *MSI = Var->getMemberSpecializationInfo(); |
| 16480 | TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() |
| 16481 | : Var->getTemplateSpecializationKind(); |
| 16482 | |
| 16483 | OdrUseContext OdrUse = isOdrUseContext(SemaRef); |
| 16484 | bool UsableInConstantExpr = |
| 16485 | Var->mightBeUsableInConstantExpressions(SemaRef.Context); |
| 16486 | |
| 16487 | // C++20 [expr.const]p12: |
| 16488 | // A variable [...] is needed for constant evaluation if it is [...] a |
| 16489 | // variable whose name appears as a potentially constant evaluated |
| 16490 | // expression that is either a contexpr variable or is of non-volatile |
| 16491 | // const-qualified integral type or of reference type |
| 16492 | bool NeededForConstantEvaluation = |
| 16493 | isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; |
| 16494 | |
| 16495 | bool NeedDefinition = |
| 16496 | OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; |
| 16497 | |
| 16498 | VarTemplateSpecializationDecl *VarSpec = |
| 16499 | dyn_cast<VarTemplateSpecializationDecl>(Var); |
| 16500 | assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && |
| 16501 | "Can't instantiate a partial template specialization." ); |
| 16502 | |
| 16503 | // If this might be a member specialization of a static data member, check |
| 16504 | // the specialization is visible. We already did the checks for variable |
| 16505 | // template specializations when we created them. |
| 16506 | if (NeedDefinition && TSK != TSK_Undeclared && |
| 16507 | !isa<VarTemplateSpecializationDecl>(Var)) |
| 16508 | SemaRef.checkSpecializationVisibility(Loc, Var); |
| 16509 | |
| 16510 | // Perform implicit instantiation of static data members, static data member |
| 16511 | // templates of class templates, and variable template specializations. Delay |
| 16512 | // instantiations of variable templates, except for those that could be used |
| 16513 | // in a constant expression. |
| 16514 | if (NeedDefinition && isTemplateInstantiation(TSK)) { |
| 16515 | // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit |
| 16516 | // instantiation declaration if a variable is usable in a constant |
| 16517 | // expression (among other cases). |
| 16518 | bool TryInstantiating = |
| 16519 | TSK == TSK_ImplicitInstantiation || |
| 16520 | (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); |
| 16521 | |
| 16522 | if (TryInstantiating) { |
| 16523 | SourceLocation PointOfInstantiation = |
| 16524 | MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); |
| 16525 | bool FirstInstantiation = PointOfInstantiation.isInvalid(); |
| 16526 | if (FirstInstantiation) { |
| 16527 | PointOfInstantiation = Loc; |
| 16528 | if (MSI) |
| 16529 | MSI->setPointOfInstantiation(PointOfInstantiation); |
| 16530 | else |
| 16531 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
| 16532 | } |
| 16533 | |
| 16534 | bool InstantiationDependent = false; |
| 16535 | bool IsNonDependent = |
| 16536 | VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( |
| 16537 | VarSpec->getTemplateArgsInfo(), InstantiationDependent) |
| 16538 | : true; |
| 16539 | |
| 16540 | // Do not instantiate specializations that are still type-dependent. |
| 16541 | if (IsNonDependent) { |
| 16542 | if (UsableInConstantExpr) { |
| 16543 | // Do not defer instantiations of variables that could be used in a |
| 16544 | // constant expression. |
| 16545 | SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); |
| 16546 | } else if (FirstInstantiation || |
| 16547 | isa<VarTemplateSpecializationDecl>(Var)) { |
| 16548 | // FIXME: For a specialization of a variable template, we don't |
| 16549 | // distinguish between "declaration and type implicitly instantiated" |
| 16550 | // and "implicit instantiation of definition requested", so we have |
| 16551 | // no direct way to avoid enqueueing the pending instantiation |
| 16552 | // multiple times. |
| 16553 | SemaRef.PendingInstantiations |
| 16554 | .push_back(std::make_pair(Var, PointOfInstantiation)); |
| 16555 | } |
| 16556 | } |
| 16557 | } |
| 16558 | } |
| 16559 | |
| 16560 | // C++2a [basic.def.odr]p4: |
| 16561 | // A variable x whose name appears as a potentially-evaluated expression e |
| 16562 | // is odr-used by e unless |
| 16563 | // -- x is a reference that is usable in constant expressions |
| 16564 | // -- x is a variable of non-reference type that is usable in constant |
| 16565 | // expressions and has no mutable subobjects [FIXME], and e is an |
| 16566 | // element of the set of potential results of an expression of |
| 16567 | // non-volatile-qualified non-class type to which the lvalue-to-rvalue |
| 16568 | // conversion is applied |
| 16569 | // -- x is a variable of non-reference type, and e is an element of the set |
| 16570 | // of potential results of a discarded-value expression to which the |
| 16571 | // lvalue-to-rvalue conversion is not applied [FIXME] |
| 16572 | // |
| 16573 | // We check the first part of the second bullet here, and |
| 16574 | // Sema::CheckLValueToRValueConversionOperand deals with the second part. |
| 16575 | // FIXME: To get the third bullet right, we need to delay this even for |
| 16576 | // variables that are not usable in constant expressions. |
| 16577 | |
| 16578 | // If we already know this isn't an odr-use, there's nothing more to do. |
| 16579 | if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) |
| 16580 | if (DRE->isNonOdrUse()) |
| 16581 | return; |
| 16582 | if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) |
| 16583 | if (ME->isNonOdrUse()) |
| 16584 | return; |
| 16585 | |
| 16586 | switch (OdrUse) { |
| 16587 | case OdrUseContext::None: |
| 16588 | assert((!E || isa<FunctionParmPackExpr>(E)) && |
| 16589 | "missing non-odr-use marking for unevaluated decl ref" ); |
| 16590 | break; |
| 16591 | |
| 16592 | case OdrUseContext::FormallyOdrUsed: |
| 16593 | // FIXME: Ignoring formal odr-uses results in incorrect lambda capture |
| 16594 | // behavior. |
| 16595 | break; |
| 16596 | |
| 16597 | case OdrUseContext::Used: |
| 16598 | // If we might later find that this expression isn't actually an odr-use, |
| 16599 | // delay the marking. |
| 16600 | if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) |
| 16601 | SemaRef.MaybeODRUseExprs.insert(E); |
| 16602 | else |
| 16603 | MarkVarDeclODRUsed(Var, Loc, SemaRef); |
| 16604 | break; |
| 16605 | |
| 16606 | case OdrUseContext::Dependent: |
| 16607 | // If this is a dependent context, we don't need to mark variables as |
| 16608 | // odr-used, but we may still need to track them for lambda capture. |
| 16609 | // FIXME: Do we also need to do this inside dependent typeid expressions |
| 16610 | // (which are modeled as unevaluated at this point)? |
| 16611 | const bool RefersToEnclosingScope = |
| 16612 | (SemaRef.CurContext != Var->getDeclContext() && |
| 16613 | Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); |
| 16614 | if (RefersToEnclosingScope) { |
| 16615 | LambdaScopeInfo *const LSI = |
| 16616 | SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); |
| 16617 | if (LSI && (!LSI->CallOperator || |
| 16618 | !LSI->CallOperator->Encloses(Var->getDeclContext()))) { |
| 16619 | // If a variable could potentially be odr-used, defer marking it so |
| 16620 | // until we finish analyzing the full expression for any |
| 16621 | // lvalue-to-rvalue |
| 16622 | // or discarded value conversions that would obviate odr-use. |
| 16623 | // Add it to the list of potential captures that will be analyzed |
| 16624 | // later (ActOnFinishFullExpr) for eventual capture and odr-use marking |
| 16625 | // unless the variable is a reference that was initialized by a constant |
| 16626 | // expression (this will never need to be captured or odr-used). |
| 16627 | // |
| 16628 | // FIXME: We can simplify this a lot after implementing P0588R1. |
| 16629 | assert(E && "Capture variable should be used in an expression." ); |
| 16630 | if (!Var->getType()->isReferenceType() || |
| 16631 | !Var->isUsableInConstantExpressions(SemaRef.Context)) |
| 16632 | LSI->addPotentialCapture(E->IgnoreParens()); |
| 16633 | } |
| 16634 | } |
| 16635 | break; |
| 16636 | } |
| 16637 | } |
| 16638 | |
| 16639 | /// Mark a variable referenced, and check whether it is odr-used |
| 16640 | /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be |
| 16641 | /// used directly for normal expressions referring to VarDecl. |
| 16642 | void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { |
| 16643 | DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); |
| 16644 | } |
| 16645 | |
| 16646 | static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, |
| 16647 | Decl *D, Expr *E, bool MightBeOdrUse) { |
| 16648 | if (SemaRef.isInOpenMPDeclareTargetContext()) |
| 16649 | SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); |
| 16650 | |
| 16651 | if (VarDecl *Var = dyn_cast<VarDecl>(D)) { |
| 16652 | DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); |
| 16653 | return; |
| 16654 | } |
| 16655 | |
| 16656 | SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); |
| 16657 | |
| 16658 | // If this is a call to a method via a cast, also mark the method in the |
| 16659 | // derived class used in case codegen can devirtualize the call. |
| 16660 | const MemberExpr *ME = dyn_cast<MemberExpr>(E); |
| 16661 | if (!ME) |
| 16662 | return; |
| 16663 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); |
| 16664 | if (!MD) |
| 16665 | return; |
| 16666 | // Only attempt to devirtualize if this is truly a virtual call. |
| 16667 | bool IsVirtualCall = MD->isVirtual() && |
| 16668 | ME->performsVirtualDispatch(SemaRef.getLangOpts()); |
| 16669 | if (!IsVirtualCall) |
| 16670 | return; |
| 16671 | |
| 16672 | // If it's possible to devirtualize the call, mark the called function |
| 16673 | // referenced. |
| 16674 | CXXMethodDecl *DM = MD->getDevirtualizedMethod( |
| 16675 | ME->getBase(), SemaRef.getLangOpts().AppleKext); |
| 16676 | if (DM) |
| 16677 | SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); |
| 16678 | } |
| 16679 | |
| 16680 | /// Perform reference-marking and odr-use handling for a DeclRefExpr. |
| 16681 | void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { |
| 16682 | // TODO: update this with DR# once a defect report is filed. |
| 16683 | // C++11 defect. The address of a pure member should not be an ODR use, even |
| 16684 | // if it's a qualified reference. |
| 16685 | bool OdrUse = true; |
| 16686 | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) |
| 16687 | if (Method->isVirtual() && |
| 16688 | !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) |
| 16689 | OdrUse = false; |
| 16690 | MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); |
| 16691 | } |
| 16692 | |
| 16693 | /// Perform reference-marking and odr-use handling for a MemberExpr. |
| 16694 | void Sema::MarkMemberReferenced(MemberExpr *E) { |
| 16695 | // C++11 [basic.def.odr]p2: |
| 16696 | // A non-overloaded function whose name appears as a potentially-evaluated |
| 16697 | // expression or a member of a set of candidate functions, if selected by |
| 16698 | // overload resolution when referred to from a potentially-evaluated |
| 16699 | // expression, is odr-used, unless it is a pure virtual function and its |
| 16700 | // name is not explicitly qualified. |
| 16701 | bool MightBeOdrUse = true; |
| 16702 | if (E->performsVirtualDispatch(getLangOpts())) { |
| 16703 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) |
| 16704 | if (Method->isPure()) |
| 16705 | MightBeOdrUse = false; |
| 16706 | } |
| 16707 | SourceLocation Loc = |
| 16708 | E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); |
| 16709 | MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); |
| 16710 | } |
| 16711 | |
| 16712 | /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. |
| 16713 | void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { |
| 16714 | for (VarDecl *VD : *E) |
| 16715 | MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); |
| 16716 | } |
| 16717 | |
| 16718 | /// Perform marking for a reference to an arbitrary declaration. It |
| 16719 | /// marks the declaration referenced, and performs odr-use checking for |
| 16720 | /// functions and variables. This method should not be used when building a |
| 16721 | /// normal expression which refers to a variable. |
| 16722 | void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, |
| 16723 | bool MightBeOdrUse) { |
| 16724 | if (MightBeOdrUse) { |
| 16725 | if (auto *VD = dyn_cast<VarDecl>(D)) { |
| 16726 | MarkVariableReferenced(Loc, VD); |
| 16727 | return; |
| 16728 | } |
| 16729 | } |
| 16730 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { |
| 16731 | MarkFunctionReferenced(Loc, FD, MightBeOdrUse); |
| 16732 | return; |
| 16733 | } |
| 16734 | D->setReferenced(); |
| 16735 | } |
| 16736 | |
| 16737 | namespace { |
| 16738 | // Mark all of the declarations used by a type as referenced. |
| 16739 | // FIXME: Not fully implemented yet! We need to have a better understanding |
| 16740 | // of when we're entering a context we should not recurse into. |
| 16741 | // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to |
| 16742 | // TreeTransforms rebuilding the type in a new context. Rather than |
| 16743 | // duplicating the TreeTransform logic, we should consider reusing it here. |
| 16744 | // Currently that causes problems when rebuilding LambdaExprs. |
| 16745 | class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { |
| 16746 | Sema &S; |
| 16747 | SourceLocation Loc; |
| 16748 | |
| 16749 | public: |
| 16750 | typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; |
| 16751 | |
| 16752 | MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } |
| 16753 | |
| 16754 | bool TraverseTemplateArgument(const TemplateArgument &Arg); |
| 16755 | }; |
| 16756 | } |
| 16757 | |
| 16758 | bool MarkReferencedDecls::TraverseTemplateArgument( |
| 16759 | const TemplateArgument &Arg) { |
| 16760 | { |
| 16761 | // A non-type template argument is a constant-evaluated context. |
| 16762 | EnterExpressionEvaluationContext Evaluated( |
| 16763 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
| 16764 | if (Arg.getKind() == TemplateArgument::Declaration) { |
| 16765 | if (Decl *D = Arg.getAsDecl()) |
| 16766 | S.MarkAnyDeclReferenced(Loc, D, true); |
| 16767 | } else if (Arg.getKind() == TemplateArgument::Expression) { |
| 16768 | S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); |
| 16769 | } |
| 16770 | } |
| 16771 | |
| 16772 | return Inherited::TraverseTemplateArgument(Arg); |
| 16773 | } |
| 16774 | |
| 16775 | void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { |
| 16776 | MarkReferencedDecls Marker(*this, Loc); |
| 16777 | Marker.TraverseType(T); |
| 16778 | } |
| 16779 | |
| 16780 | namespace { |
| 16781 | /// Helper class that marks all of the declarations referenced by |
| 16782 | /// potentially-evaluated subexpressions as "referenced". |
| 16783 | class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { |
| 16784 | Sema &S; |
| 16785 | bool SkipLocalVariables; |
| 16786 | |
| 16787 | public: |
| 16788 | typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; |
| 16789 | |
| 16790 | EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) |
| 16791 | : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } |
| 16792 | |
| 16793 | void VisitDeclRefExpr(DeclRefExpr *E) { |
| 16794 | // If we were asked not to visit local variables, don't. |
| 16795 | if (SkipLocalVariables) { |
| 16796 | if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) |
| 16797 | if (VD->hasLocalStorage()) |
| 16798 | return; |
| 16799 | } |
| 16800 | |
| 16801 | S.MarkDeclRefReferenced(E); |
| 16802 | } |
| 16803 | |
| 16804 | void VisitMemberExpr(MemberExpr *E) { |
| 16805 | S.MarkMemberReferenced(E); |
| 16806 | Inherited::VisitMemberExpr(E); |
| 16807 | } |
| 16808 | |
| 16809 | void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { |
| 16810 | S.MarkFunctionReferenced( |
| 16811 | E->getBeginLoc(), |
| 16812 | const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); |
| 16813 | Visit(E->getSubExpr()); |
| 16814 | } |
| 16815 | |
| 16816 | void VisitCXXNewExpr(CXXNewExpr *E) { |
| 16817 | if (E->getOperatorNew()) |
| 16818 | S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); |
| 16819 | if (E->getOperatorDelete()) |
| 16820 | S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); |
| 16821 | Inherited::VisitCXXNewExpr(E); |
| 16822 | } |
| 16823 | |
| 16824 | void VisitCXXDeleteExpr(CXXDeleteExpr *E) { |
| 16825 | if (E->getOperatorDelete()) |
| 16826 | S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); |
| 16827 | QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); |
| 16828 | if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { |
| 16829 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); |
| 16830 | S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); |
| 16831 | } |
| 16832 | |
| 16833 | Inherited::VisitCXXDeleteExpr(E); |
| 16834 | } |
| 16835 | |
| 16836 | void VisitCXXConstructExpr(CXXConstructExpr *E) { |
| 16837 | S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); |
| 16838 | Inherited::VisitCXXConstructExpr(E); |
| 16839 | } |
| 16840 | |
| 16841 | void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { |
| 16842 | Visit(E->getExpr()); |
| 16843 | } |
| 16844 | }; |
| 16845 | } |
| 16846 | |
| 16847 | /// Mark any declarations that appear within this expression or any |
| 16848 | /// potentially-evaluated subexpressions as "referenced". |
| 16849 | /// |
| 16850 | /// \param SkipLocalVariables If true, don't mark local variables as |
| 16851 | /// 'referenced'. |
| 16852 | void Sema::MarkDeclarationsReferencedInExpr(Expr *E, |
| 16853 | bool SkipLocalVariables) { |
| 16854 | EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); |
| 16855 | } |
| 16856 | |
| 16857 | /// Emit a diagnostic that describes an effect on the run-time behavior |
| 16858 | /// of the program being compiled. |
| 16859 | /// |
| 16860 | /// This routine emits the given diagnostic when the code currently being |
| 16861 | /// type-checked is "potentially evaluated", meaning that there is a |
| 16862 | /// possibility that the code will actually be executable. Code in sizeof() |
| 16863 | /// expressions, code used only during overload resolution, etc., are not |
| 16864 | /// potentially evaluated. This routine will suppress such diagnostics or, |
| 16865 | /// in the absolutely nutty case of potentially potentially evaluated |
| 16866 | /// expressions (C++ typeid), queue the diagnostic to potentially emit it |
| 16867 | /// later. |
| 16868 | /// |
| 16869 | /// This routine should be used for all diagnostics that describe the run-time |
| 16870 | /// behavior of a program, such as passing a non-POD value through an ellipsis. |
| 16871 | /// Failure to do so will likely result in spurious diagnostics or failures |
| 16872 | /// during overload resolution or within sizeof/alignof/typeof/typeid. |
| 16873 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, |
| 16874 | const PartialDiagnostic &PD) { |
| 16875 | switch (ExprEvalContexts.back().Context) { |
| 16876 | case ExpressionEvaluationContext::Unevaluated: |
| 16877 | case ExpressionEvaluationContext::UnevaluatedList: |
| 16878 | case ExpressionEvaluationContext::UnevaluatedAbstract: |
| 16879 | case ExpressionEvaluationContext::DiscardedStatement: |
| 16880 | // The argument will never be evaluated, so don't complain. |
| 16881 | break; |
| 16882 | |
| 16883 | case ExpressionEvaluationContext::ConstantEvaluated: |
| 16884 | // Relevant diagnostics should be produced by constant evaluation. |
| 16885 | break; |
| 16886 | |
| 16887 | case ExpressionEvaluationContext::PotentiallyEvaluated: |
| 16888 | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
| 16889 | if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { |
| 16890 | FunctionScopes.back()->PossiblyUnreachableDiags. |
| 16891 | push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); |
| 16892 | return true; |
| 16893 | } |
| 16894 | |
| 16895 | // The initializer of a constexpr variable or of the first declaration of a |
| 16896 | // static data member is not syntactically a constant evaluated constant, |
| 16897 | // but nonetheless is always required to be a constant expression, so we |
| 16898 | // can skip diagnosing. |
| 16899 | // FIXME: Using the mangling context here is a hack. |
| 16900 | if (auto *VD = dyn_cast_or_null<VarDecl>( |
| 16901 | ExprEvalContexts.back().ManglingContextDecl)) { |
| 16902 | if (VD->isConstexpr() || |
| 16903 | (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) |
| 16904 | break; |
| 16905 | // FIXME: For any other kind of variable, we should build a CFG for its |
| 16906 | // initializer and check whether the context in question is reachable. |
| 16907 | } |
| 16908 | |
| 16909 | Diag(Loc, PD); |
| 16910 | return true; |
| 16911 | } |
| 16912 | |
| 16913 | return false; |
| 16914 | } |
| 16915 | |
| 16916 | bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, |
| 16917 | const PartialDiagnostic &PD) { |
| 16918 | return DiagRuntimeBehavior( |
| 16919 | Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); |
| 16920 | } |
| 16921 | |
| 16922 | bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, |
| 16923 | CallExpr *CE, FunctionDecl *FD) { |
| 16924 | if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) |
| 16925 | return false; |
| 16926 | |
| 16927 | // If we're inside a decltype's expression, don't check for a valid return |
| 16928 | // type or construct temporaries until we know whether this is the last call. |
| 16929 | if (ExprEvalContexts.back().ExprContext == |
| 16930 | ExpressionEvaluationContextRecord::EK_Decltype) { |
| 16931 | ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); |
| 16932 | return false; |
| 16933 | } |
| 16934 | |
| 16935 | class CallReturnIncompleteDiagnoser : public TypeDiagnoser { |
| 16936 | FunctionDecl *FD; |
| 16937 | CallExpr *CE; |
| 16938 | |
| 16939 | public: |
| 16940 | CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) |
| 16941 | : FD(FD), CE(CE) { } |
| 16942 | |
| 16943 | void diagnose(Sema &S, SourceLocation Loc, QualType T) override { |
| 16944 | if (!FD) { |
| 16945 | S.Diag(Loc, diag::err_call_incomplete_return) |
| 16946 | << T << CE->getSourceRange(); |
| 16947 | return; |
| 16948 | } |
| 16949 | |
| 16950 | S.Diag(Loc, diag::err_call_function_incomplete_return) |
| 16951 | << CE->getSourceRange() << FD->getDeclName() << T; |
| 16952 | S.Diag(FD->getLocation(), diag::note_entity_declared_at) |
| 16953 | << FD->getDeclName(); |
| 16954 | } |
| 16955 | } Diagnoser(FD, CE); |
| 16956 | |
| 16957 | if (RequireCompleteType(Loc, ReturnType, Diagnoser)) |
| 16958 | return true; |
| 16959 | |
| 16960 | return false; |
| 16961 | } |
| 16962 | |
| 16963 | // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses |
| 16964 | // will prevent this condition from triggering, which is what we want. |
| 16965 | void Sema::DiagnoseAssignmentAsCondition(Expr *E) { |
| 16966 | SourceLocation Loc; |
| 16967 | |
| 16968 | unsigned diagnostic = diag::warn_condition_is_assignment; |
| 16969 | bool IsOrAssign = false; |
| 16970 | |
| 16971 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { |
| 16972 | if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) |
| 16973 | return; |
| 16974 | |
| 16975 | IsOrAssign = Op->getOpcode() == BO_OrAssign; |
| 16976 | |
| 16977 | // Greylist some idioms by putting them into a warning subcategory. |
| 16978 | if (ObjCMessageExpr *ME |
| 16979 | = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { |
| 16980 | Selector Sel = ME->getSelector(); |
| 16981 | |
| 16982 | // self = [<foo> init...] |
| 16983 | if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) |
| 16984 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
| 16985 | |
| 16986 | // <foo> = [<bar> nextObject] |
| 16987 | else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject" ) |
| 16988 | diagnostic = diag::warn_condition_is_idiomatic_assignment; |
| 16989 | } |
| 16990 | |
| 16991 | Loc = Op->getOperatorLoc(); |
| 16992 | } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { |
| 16993 | if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) |
| 16994 | return; |
| 16995 | |
| 16996 | IsOrAssign = Op->getOperator() == OO_PipeEqual; |
| 16997 | Loc = Op->getOperatorLoc(); |
| 16998 | } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) |
| 16999 | return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); |
| 17000 | else { |
| 17001 | // Not an assignment. |
| 17002 | return; |
| 17003 | } |
| 17004 | |
| 17005 | Diag(Loc, diagnostic) << E->getSourceRange(); |
| 17006 | |
| 17007 | SourceLocation Open = E->getBeginLoc(); |
| 17008 | SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); |
| 17009 | Diag(Loc, diag::note_condition_assign_silence) |
| 17010 | << FixItHint::CreateInsertion(Open, "(" ) |
| 17011 | << FixItHint::CreateInsertion(Close, ")" ); |
| 17012 | |
| 17013 | if (IsOrAssign) |
| 17014 | Diag(Loc, diag::note_condition_or_assign_to_comparison) |
| 17015 | << FixItHint::CreateReplacement(Loc, "!=" ); |
| 17016 | else |
| 17017 | Diag(Loc, diag::note_condition_assign_to_comparison) |
| 17018 | << FixItHint::CreateReplacement(Loc, "==" ); |
| 17019 | } |
| 17020 | |
| 17021 | /// Redundant parentheses over an equality comparison can indicate |
| 17022 | /// that the user intended an assignment used as condition. |
| 17023 | void Sema::(ParenExpr *ParenE) { |
| 17024 | // Don't warn if the parens came from a macro. |
| 17025 | SourceLocation parenLoc = ParenE->getBeginLoc(); |
| 17026 | if (parenLoc.isInvalid() || parenLoc.isMacroID()) |
| 17027 | return; |
| 17028 | // Don't warn for dependent expressions. |
| 17029 | if (ParenE->isTypeDependent()) |
| 17030 | return; |
| 17031 | |
| 17032 | Expr *E = ParenE->IgnoreParens(); |
| 17033 | |
| 17034 | if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) |
| 17035 | if (opE->getOpcode() == BO_EQ && |
| 17036 | opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) |
| 17037 | == Expr::MLV_Valid) { |
| 17038 | SourceLocation Loc = opE->getOperatorLoc(); |
| 17039 | |
| 17040 | Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); |
| 17041 | SourceRange ParenERange = ParenE->getSourceRange(); |
| 17042 | Diag(Loc, diag::note_equality_comparison_silence) |
| 17043 | << FixItHint::CreateRemoval(ParenERange.getBegin()) |
| 17044 | << FixItHint::CreateRemoval(ParenERange.getEnd()); |
| 17045 | Diag(Loc, diag::note_equality_comparison_to_assign) |
| 17046 | << FixItHint::CreateReplacement(Loc, "=" ); |
| 17047 | } |
| 17048 | } |
| 17049 | |
| 17050 | ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, |
| 17051 | bool IsConstexpr) { |
| 17052 | DiagnoseAssignmentAsCondition(E); |
| 17053 | if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) |
| 17054 | DiagnoseEqualityWithExtraParens(parenE); |
| 17055 | |
| 17056 | ExprResult result = CheckPlaceholderExpr(E); |
| 17057 | if (result.isInvalid()) return ExprError(); |
| 17058 | E = result.get(); |
| 17059 | |
| 17060 | if (!E->isTypeDependent()) { |
| 17061 | if (getLangOpts().CPlusPlus) |
| 17062 | return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 |
| 17063 | |
| 17064 | ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); |
| 17065 | if (ERes.isInvalid()) |
| 17066 | return ExprError(); |
| 17067 | E = ERes.get(); |
| 17068 | |
| 17069 | QualType T = E->getType(); |
| 17070 | if (!T->isScalarType()) { // C99 6.8.4.1p1 |
| 17071 | Diag(Loc, diag::err_typecheck_statement_requires_scalar) |
| 17072 | << T << E->getSourceRange(); |
| 17073 | return ExprError(); |
| 17074 | } |
| 17075 | CheckBoolLikeConversion(E, Loc); |
| 17076 | } |
| 17077 | |
| 17078 | return E; |
| 17079 | } |
| 17080 | |
| 17081 | Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, |
| 17082 | Expr *SubExpr, ConditionKind CK) { |
| 17083 | // Empty conditions are valid in for-statements. |
| 17084 | if (!SubExpr) |
| 17085 | return ConditionResult(); |
| 17086 | |
| 17087 | ExprResult Cond; |
| 17088 | switch (CK) { |
| 17089 | case ConditionKind::Boolean: |
| 17090 | Cond = CheckBooleanCondition(Loc, SubExpr); |
| 17091 | break; |
| 17092 | |
| 17093 | case ConditionKind::ConstexprIf: |
| 17094 | Cond = CheckBooleanCondition(Loc, SubExpr, true); |
| 17095 | break; |
| 17096 | |
| 17097 | case ConditionKind::Switch: |
| 17098 | Cond = CheckSwitchCondition(Loc, SubExpr); |
| 17099 | break; |
| 17100 | } |
| 17101 | if (Cond.isInvalid()) |
| 17102 | return ConditionError(); |
| 17103 | |
| 17104 | // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. |
| 17105 | FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); |
| 17106 | if (!FullExpr.get()) |
| 17107 | return ConditionError(); |
| 17108 | |
| 17109 | return ConditionResult(*this, nullptr, FullExpr, |
| 17110 | CK == ConditionKind::ConstexprIf); |
| 17111 | } |
| 17112 | |
| 17113 | namespace { |
| 17114 | /// A visitor for rebuilding a call to an __unknown_any expression |
| 17115 | /// to have an appropriate type. |
| 17116 | struct RebuildUnknownAnyFunction |
| 17117 | : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { |
| 17118 | |
| 17119 | Sema &S; |
| 17120 | |
| 17121 | RebuildUnknownAnyFunction(Sema &S) : S(S) {} |
| 17122 | |
| 17123 | ExprResult VisitStmt(Stmt *S) { |
| 17124 | llvm_unreachable("unexpected statement!" ); |
| 17125 | } |
| 17126 | |
| 17127 | ExprResult VisitExpr(Expr *E) { |
| 17128 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) |
| 17129 | << E->getSourceRange(); |
| 17130 | return ExprError(); |
| 17131 | } |
| 17132 | |
| 17133 | /// Rebuild an expression which simply semantically wraps another |
| 17134 | /// expression which it shares the type and value kind of. |
| 17135 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
| 17136 | ExprResult SubResult = Visit(E->getSubExpr()); |
| 17137 | if (SubResult.isInvalid()) return ExprError(); |
| 17138 | |
| 17139 | Expr *SubExpr = SubResult.get(); |
| 17140 | E->setSubExpr(SubExpr); |
| 17141 | E->setType(SubExpr->getType()); |
| 17142 | E->setValueKind(SubExpr->getValueKind()); |
| 17143 | assert(E->getObjectKind() == OK_Ordinary); |
| 17144 | return E; |
| 17145 | } |
| 17146 | |
| 17147 | ExprResult VisitParenExpr(ParenExpr *E) { |
| 17148 | return rebuildSugarExpr(E); |
| 17149 | } |
| 17150 | |
| 17151 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
| 17152 | return rebuildSugarExpr(E); |
| 17153 | } |
| 17154 | |
| 17155 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
| 17156 | ExprResult SubResult = Visit(E->getSubExpr()); |
| 17157 | if (SubResult.isInvalid()) return ExprError(); |
| 17158 | |
| 17159 | Expr *SubExpr = SubResult.get(); |
| 17160 | E->setSubExpr(SubExpr); |
| 17161 | E->setType(S.Context.getPointerType(SubExpr->getType())); |
| 17162 | assert(E->getValueKind() == VK_RValue); |
| 17163 | assert(E->getObjectKind() == OK_Ordinary); |
| 17164 | return E; |
| 17165 | } |
| 17166 | |
| 17167 | ExprResult resolveDecl(Expr *E, ValueDecl *VD) { |
| 17168 | if (!isa<FunctionDecl>(VD)) return VisitExpr(E); |
| 17169 | |
| 17170 | E->setType(VD->getType()); |
| 17171 | |
| 17172 | assert(E->getValueKind() == VK_RValue); |
| 17173 | if (S.getLangOpts().CPlusPlus && |
| 17174 | !(isa<CXXMethodDecl>(VD) && |
| 17175 | cast<CXXMethodDecl>(VD)->isInstance())) |
| 17176 | E->setValueKind(VK_LValue); |
| 17177 | |
| 17178 | return E; |
| 17179 | } |
| 17180 | |
| 17181 | ExprResult VisitMemberExpr(MemberExpr *E) { |
| 17182 | return resolveDecl(E, E->getMemberDecl()); |
| 17183 | } |
| 17184 | |
| 17185 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
| 17186 | return resolveDecl(E, E->getDecl()); |
| 17187 | } |
| 17188 | }; |
| 17189 | } |
| 17190 | |
| 17191 | /// Given a function expression of unknown-any type, try to rebuild it |
| 17192 | /// to have a function type. |
| 17193 | static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { |
| 17194 | ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); |
| 17195 | if (Result.isInvalid()) return ExprError(); |
| 17196 | return S.DefaultFunctionArrayConversion(Result.get()); |
| 17197 | } |
| 17198 | |
| 17199 | namespace { |
| 17200 | /// A visitor for rebuilding an expression of type __unknown_anytype |
| 17201 | /// into one which resolves the type directly on the referring |
| 17202 | /// expression. Strict preservation of the original source |
| 17203 | /// structure is not a goal. |
| 17204 | struct RebuildUnknownAnyExpr |
| 17205 | : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { |
| 17206 | |
| 17207 | Sema &S; |
| 17208 | |
| 17209 | /// The current destination type. |
| 17210 | QualType DestType; |
| 17211 | |
| 17212 | RebuildUnknownAnyExpr(Sema &S, QualType CastType) |
| 17213 | : S(S), DestType(CastType) {} |
| 17214 | |
| 17215 | ExprResult VisitStmt(Stmt *S) { |
| 17216 | llvm_unreachable("unexpected statement!" ); |
| 17217 | } |
| 17218 | |
| 17219 | ExprResult VisitExpr(Expr *E) { |
| 17220 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) |
| 17221 | << E->getSourceRange(); |
| 17222 | return ExprError(); |
| 17223 | } |
| 17224 | |
| 17225 | ExprResult VisitCallExpr(CallExpr *E); |
| 17226 | ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); |
| 17227 | |
| 17228 | /// Rebuild an expression which simply semantically wraps another |
| 17229 | /// expression which it shares the type and value kind of. |
| 17230 | template <class T> ExprResult rebuildSugarExpr(T *E) { |
| 17231 | ExprResult SubResult = Visit(E->getSubExpr()); |
| 17232 | if (SubResult.isInvalid()) return ExprError(); |
| 17233 | Expr *SubExpr = SubResult.get(); |
| 17234 | E->setSubExpr(SubExpr); |
| 17235 | E->setType(SubExpr->getType()); |
| 17236 | E->setValueKind(SubExpr->getValueKind()); |
| 17237 | assert(E->getObjectKind() == OK_Ordinary); |
| 17238 | return E; |
| 17239 | } |
| 17240 | |
| 17241 | ExprResult VisitParenExpr(ParenExpr *E) { |
| 17242 | return rebuildSugarExpr(E); |
| 17243 | } |
| 17244 | |
| 17245 | ExprResult VisitUnaryExtension(UnaryOperator *E) { |
| 17246 | return rebuildSugarExpr(E); |
| 17247 | } |
| 17248 | |
| 17249 | ExprResult VisitUnaryAddrOf(UnaryOperator *E) { |
| 17250 | const PointerType *Ptr = DestType->getAs<PointerType>(); |
| 17251 | if (!Ptr) { |
| 17252 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) |
| 17253 | << E->getSourceRange(); |
| 17254 | return ExprError(); |
| 17255 | } |
| 17256 | |
| 17257 | if (isa<CallExpr>(E->getSubExpr())) { |
| 17258 | S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) |
| 17259 | << E->getSourceRange(); |
| 17260 | return ExprError(); |
| 17261 | } |
| 17262 | |
| 17263 | assert(E->getValueKind() == VK_RValue); |
| 17264 | assert(E->getObjectKind() == OK_Ordinary); |
| 17265 | E->setType(DestType); |
| 17266 | |
| 17267 | // Build the sub-expression as if it were an object of the pointee type. |
| 17268 | DestType = Ptr->getPointeeType(); |
| 17269 | ExprResult SubResult = Visit(E->getSubExpr()); |
| 17270 | if (SubResult.isInvalid()) return ExprError(); |
| 17271 | E->setSubExpr(SubResult.get()); |
| 17272 | return E; |
| 17273 | } |
| 17274 | |
| 17275 | ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); |
| 17276 | |
| 17277 | ExprResult resolveDecl(Expr *E, ValueDecl *VD); |
| 17278 | |
| 17279 | ExprResult VisitMemberExpr(MemberExpr *E) { |
| 17280 | return resolveDecl(E, E->getMemberDecl()); |
| 17281 | } |
| 17282 | |
| 17283 | ExprResult VisitDeclRefExpr(DeclRefExpr *E) { |
| 17284 | return resolveDecl(E, E->getDecl()); |
| 17285 | } |
| 17286 | }; |
| 17287 | } |
| 17288 | |
| 17289 | /// Rebuilds a call expression which yielded __unknown_anytype. |
| 17290 | ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { |
| 17291 | Expr *CalleeExpr = E->getCallee(); |
| 17292 | |
| 17293 | enum FnKind { |
| 17294 | FK_MemberFunction, |
| 17295 | FK_FunctionPointer, |
| 17296 | FK_BlockPointer |
| 17297 | }; |
| 17298 | |
| 17299 | FnKind Kind; |
| 17300 | QualType CalleeType = CalleeExpr->getType(); |
| 17301 | if (CalleeType == S.Context.BoundMemberTy) { |
| 17302 | assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); |
| 17303 | Kind = FK_MemberFunction; |
| 17304 | CalleeType = Expr::findBoundMemberType(CalleeExpr); |
| 17305 | } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { |
| 17306 | CalleeType = Ptr->getPointeeType(); |
| 17307 | Kind = FK_FunctionPointer; |
| 17308 | } else { |
| 17309 | CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); |
| 17310 | Kind = FK_BlockPointer; |
| 17311 | } |
| 17312 | const FunctionType *FnType = CalleeType->castAs<FunctionType>(); |
| 17313 | |
| 17314 | // Verify that this is a legal result type of a function. |
| 17315 | if (DestType->isArrayType() || DestType->isFunctionType()) { |
| 17316 | unsigned diagID = diag::err_func_returning_array_function; |
| 17317 | if (Kind == FK_BlockPointer) |
| 17318 | diagID = diag::err_block_returning_array_function; |
| 17319 | |
| 17320 | S.Diag(E->getExprLoc(), diagID) |
| 17321 | << DestType->isFunctionType() << DestType; |
| 17322 | return ExprError(); |
| 17323 | } |
| 17324 | |
| 17325 | // Otherwise, go ahead and set DestType as the call's result. |
| 17326 | E->setType(DestType.getNonLValueExprType(S.Context)); |
| 17327 | E->setValueKind(Expr::getValueKindForType(DestType)); |
| 17328 | assert(E->getObjectKind() == OK_Ordinary); |
| 17329 | |
| 17330 | // Rebuild the function type, replacing the result type with DestType. |
| 17331 | const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); |
| 17332 | if (Proto) { |
| 17333 | // __unknown_anytype(...) is a special case used by the debugger when |
| 17334 | // it has no idea what a function's signature is. |
| 17335 | // |
| 17336 | // We want to build this call essentially under the K&R |
| 17337 | // unprototyped rules, but making a FunctionNoProtoType in C++ |
| 17338 | // would foul up all sorts of assumptions. However, we cannot |
| 17339 | // simply pass all arguments as variadic arguments, nor can we |
| 17340 | // portably just call the function under a non-variadic type; see |
| 17341 | // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. |
| 17342 | // However, it turns out that in practice it is generally safe to |
| 17343 | // call a function declared as "A foo(B,C,D);" under the prototype |
| 17344 | // "A foo(B,C,D,...);". The only known exception is with the |
| 17345 | // Windows ABI, where any variadic function is implicitly cdecl |
| 17346 | // regardless of its normal CC. Therefore we change the parameter |
| 17347 | // types to match the types of the arguments. |
| 17348 | // |
| 17349 | // This is a hack, but it is far superior to moving the |
| 17350 | // corresponding target-specific code from IR-gen to Sema/AST. |
| 17351 | |
| 17352 | ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); |
| 17353 | SmallVector<QualType, 8> ArgTypes; |
| 17354 | if (ParamTypes.empty() && Proto->isVariadic()) { // the special case |
| 17355 | ArgTypes.reserve(E->getNumArgs()); |
| 17356 | for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { |
| 17357 | Expr *Arg = E->getArg(i); |
| 17358 | QualType ArgType = Arg->getType(); |
| 17359 | if (E->isLValue()) { |
| 17360 | ArgType = S.Context.getLValueReferenceType(ArgType); |
| 17361 | } else if (E->isXValue()) { |
| 17362 | ArgType = S.Context.getRValueReferenceType(ArgType); |
| 17363 | } |
| 17364 | ArgTypes.push_back(ArgType); |
| 17365 | } |
| 17366 | ParamTypes = ArgTypes; |
| 17367 | } |
| 17368 | DestType = S.Context.getFunctionType(DestType, ParamTypes, |
| 17369 | Proto->getExtProtoInfo()); |
| 17370 | } else { |
| 17371 | DestType = S.Context.getFunctionNoProtoType(DestType, |
| 17372 | FnType->getExtInfo()); |
| 17373 | } |
| 17374 | |
| 17375 | // Rebuild the appropriate pointer-to-function type. |
| 17376 | switch (Kind) { |
| 17377 | case FK_MemberFunction: |
| 17378 | // Nothing to do. |
| 17379 | break; |
| 17380 | |
| 17381 | case FK_FunctionPointer: |
| 17382 | DestType = S.Context.getPointerType(DestType); |
| 17383 | break; |
| 17384 | |
| 17385 | case FK_BlockPointer: |
| 17386 | DestType = S.Context.getBlockPointerType(DestType); |
| 17387 | break; |
| 17388 | } |
| 17389 | |
| 17390 | // Finally, we can recurse. |
| 17391 | ExprResult CalleeResult = Visit(CalleeExpr); |
| 17392 | if (!CalleeResult.isUsable()) return ExprError(); |
| 17393 | E->setCallee(CalleeResult.get()); |
| 17394 | |
| 17395 | // Bind a temporary if necessary. |
| 17396 | return S.MaybeBindToTemporary(E); |
| 17397 | } |
| 17398 | |
| 17399 | ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { |
| 17400 | // Verify that this is a legal result type of a call. |
| 17401 | if (DestType->isArrayType() || DestType->isFunctionType()) { |
| 17402 | S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) |
| 17403 | << DestType->isFunctionType() << DestType; |
| 17404 | return ExprError(); |
| 17405 | } |
| 17406 | |
| 17407 | // Rewrite the method result type if available. |
| 17408 | if (ObjCMethodDecl *Method = E->getMethodDecl()) { |
| 17409 | assert(Method->getReturnType() == S.Context.UnknownAnyTy); |
| 17410 | Method->setReturnType(DestType); |
| 17411 | } |
| 17412 | |
| 17413 | // Change the type of the message. |
| 17414 | E->setType(DestType.getNonReferenceType()); |
| 17415 | E->setValueKind(Expr::getValueKindForType(DestType)); |
| 17416 | |
| 17417 | return S.MaybeBindToTemporary(E); |
| 17418 | } |
| 17419 | |
| 17420 | ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { |
| 17421 | // The only case we should ever see here is a function-to-pointer decay. |
| 17422 | if (E->getCastKind() == CK_FunctionToPointerDecay) { |
| 17423 | assert(E->getValueKind() == VK_RValue); |
| 17424 | assert(E->getObjectKind() == OK_Ordinary); |
| 17425 | |
| 17426 | E->setType(DestType); |
| 17427 | |
| 17428 | // Rebuild the sub-expression as the pointee (function) type. |
| 17429 | DestType = DestType->castAs<PointerType>()->getPointeeType(); |
| 17430 | |
| 17431 | ExprResult Result = Visit(E->getSubExpr()); |
| 17432 | if (!Result.isUsable()) return ExprError(); |
| 17433 | |
| 17434 | E->setSubExpr(Result.get()); |
| 17435 | return E; |
| 17436 | } else if (E->getCastKind() == CK_LValueToRValue) { |
| 17437 | assert(E->getValueKind() == VK_RValue); |
| 17438 | assert(E->getObjectKind() == OK_Ordinary); |
| 17439 | |
| 17440 | assert(isa<BlockPointerType>(E->getType())); |
| 17441 | |
| 17442 | E->setType(DestType); |
| 17443 | |
| 17444 | // The sub-expression has to be a lvalue reference, so rebuild it as such. |
| 17445 | DestType = S.Context.getLValueReferenceType(DestType); |
| 17446 | |
| 17447 | ExprResult Result = Visit(E->getSubExpr()); |
| 17448 | if (!Result.isUsable()) return ExprError(); |
| 17449 | |
| 17450 | E->setSubExpr(Result.get()); |
| 17451 | return E; |
| 17452 | } else { |
| 17453 | llvm_unreachable("Unhandled cast type!" ); |
| 17454 | } |
| 17455 | } |
| 17456 | |
| 17457 | ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { |
| 17458 | ExprValueKind ValueKind = VK_LValue; |
| 17459 | QualType Type = DestType; |
| 17460 | |
| 17461 | // We know how to make this work for certain kinds of decls: |
| 17462 | |
| 17463 | // - functions |
| 17464 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { |
| 17465 | if (const PointerType *Ptr = Type->getAs<PointerType>()) { |
| 17466 | DestType = Ptr->getPointeeType(); |
| 17467 | ExprResult Result = resolveDecl(E, VD); |
| 17468 | if (Result.isInvalid()) return ExprError(); |
| 17469 | return S.ImpCastExprToType(Result.get(), Type, |
| 17470 | CK_FunctionToPointerDecay, VK_RValue); |
| 17471 | } |
| 17472 | |
| 17473 | if (!Type->isFunctionType()) { |
| 17474 | S.Diag(E->getExprLoc(), diag::err_unknown_any_function) |
| 17475 | << VD << E->getSourceRange(); |
| 17476 | return ExprError(); |
| 17477 | } |
| 17478 | if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { |
| 17479 | // We must match the FunctionDecl's type to the hack introduced in |
| 17480 | // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown |
| 17481 | // type. See the lengthy commentary in that routine. |
| 17482 | QualType FDT = FD->getType(); |
| 17483 | const FunctionType *FnType = FDT->castAs<FunctionType>(); |
| 17484 | const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); |
| 17485 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); |
| 17486 | if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { |
| 17487 | SourceLocation Loc = FD->getLocation(); |
| 17488 | FunctionDecl *NewFD = FunctionDecl::Create(S.Context, |
| 17489 | FD->getDeclContext(), |
| 17490 | Loc, Loc, FD->getNameInfo().getName(), |
| 17491 | DestType, FD->getTypeSourceInfo(), |
| 17492 | SC_None, false/*isInlineSpecified*/, |
| 17493 | FD->hasPrototype(), |
| 17494 | false/*isConstexprSpecified*/); |
| 17495 | |
| 17496 | if (FD->getQualifier()) |
| 17497 | NewFD->setQualifierInfo(FD->getQualifierLoc()); |
| 17498 | |
| 17499 | SmallVector<ParmVarDecl*, 16> Params; |
| 17500 | for (const auto &AI : FT->param_types()) { |
| 17501 | ParmVarDecl *Param = |
| 17502 | S.BuildParmVarDeclForTypedef(FD, Loc, AI); |
| 17503 | Param->setScopeInfo(0, Params.size()); |
| 17504 | Params.push_back(Param); |
| 17505 | } |
| 17506 | NewFD->setParams(Params); |
| 17507 | DRE->setDecl(NewFD); |
| 17508 | VD = DRE->getDecl(); |
| 17509 | } |
| 17510 | } |
| 17511 | |
| 17512 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) |
| 17513 | if (MD->isInstance()) { |
| 17514 | ValueKind = VK_RValue; |
| 17515 | Type = S.Context.BoundMemberTy; |
| 17516 | } |
| 17517 | |
| 17518 | // Function references aren't l-values in C. |
| 17519 | if (!S.getLangOpts().CPlusPlus) |
| 17520 | ValueKind = VK_RValue; |
| 17521 | |
| 17522 | // - variables |
| 17523 | } else if (isa<VarDecl>(VD)) { |
| 17524 | if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { |
| 17525 | Type = RefTy->getPointeeType(); |
| 17526 | } else if (Type->isFunctionType()) { |
| 17527 | S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) |
| 17528 | << VD << E->getSourceRange(); |
| 17529 | return ExprError(); |
| 17530 | } |
| 17531 | |
| 17532 | // - nothing else |
| 17533 | } else { |
| 17534 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) |
| 17535 | << VD << E->getSourceRange(); |
| 17536 | return ExprError(); |
| 17537 | } |
| 17538 | |
| 17539 | // Modifying the declaration like this is friendly to IR-gen but |
| 17540 | // also really dangerous. |
| 17541 | VD->setType(DestType); |
| 17542 | E->setType(Type); |
| 17543 | E->setValueKind(ValueKind); |
| 17544 | return E; |
| 17545 | } |
| 17546 | |
| 17547 | /// Check a cast of an unknown-any type. We intentionally only |
| 17548 | /// trigger this for C-style casts. |
| 17549 | ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, |
| 17550 | Expr *CastExpr, CastKind &CastKind, |
| 17551 | ExprValueKind &VK, CXXCastPath &Path) { |
| 17552 | // The type we're casting to must be either void or complete. |
| 17553 | if (!CastType->isVoidType() && |
| 17554 | RequireCompleteType(TypeRange.getBegin(), CastType, |
| 17555 | diag::err_typecheck_cast_to_incomplete)) |
| 17556 | return ExprError(); |
| 17557 | |
| 17558 | // Rewrite the casted expression from scratch. |
| 17559 | ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); |
| 17560 | if (!result.isUsable()) return ExprError(); |
| 17561 | |
| 17562 | CastExpr = result.get(); |
| 17563 | VK = CastExpr->getValueKind(); |
| 17564 | CastKind = CK_NoOp; |
| 17565 | |
| 17566 | return CastExpr; |
| 17567 | } |
| 17568 | |
| 17569 | ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { |
| 17570 | return RebuildUnknownAnyExpr(*this, ToType).Visit(E); |
| 17571 | } |
| 17572 | |
| 17573 | ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, |
| 17574 | Expr *arg, QualType ¶mType) { |
| 17575 | // If the syntactic form of the argument is not an explicit cast of |
| 17576 | // any sort, just do default argument promotion. |
| 17577 | ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); |
| 17578 | if (!castArg) { |
| 17579 | ExprResult result = DefaultArgumentPromotion(arg); |
| 17580 | if (result.isInvalid()) return ExprError(); |
| 17581 | paramType = result.get()->getType(); |
| 17582 | return result; |
| 17583 | } |
| 17584 | |
| 17585 | // Otherwise, use the type that was written in the explicit cast. |
| 17586 | assert(!arg->hasPlaceholderType()); |
| 17587 | paramType = castArg->getTypeAsWritten(); |
| 17588 | |
| 17589 | // Copy-initialize a parameter of that type. |
| 17590 | InitializedEntity entity = |
| 17591 | InitializedEntity::InitializeParameter(Context, paramType, |
| 17592 | /*consumed*/ false); |
| 17593 | return PerformCopyInitialization(entity, callLoc, arg); |
| 17594 | } |
| 17595 | |
| 17596 | static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { |
| 17597 | Expr *orig = E; |
| 17598 | unsigned diagID = diag::err_uncasted_use_of_unknown_any; |
| 17599 | while (true) { |
| 17600 | E = E->IgnoreParenImpCasts(); |
| 17601 | if (CallExpr *call = dyn_cast<CallExpr>(E)) { |
| 17602 | E = call->getCallee(); |
| 17603 | diagID = diag::err_uncasted_call_of_unknown_any; |
| 17604 | } else { |
| 17605 | break; |
| 17606 | } |
| 17607 | } |
| 17608 | |
| 17609 | SourceLocation loc; |
| 17610 | NamedDecl *d; |
| 17611 | if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { |
| 17612 | loc = ref->getLocation(); |
| 17613 | d = ref->getDecl(); |
| 17614 | } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { |
| 17615 | loc = mem->getMemberLoc(); |
| 17616 | d = mem->getMemberDecl(); |
| 17617 | } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { |
| 17618 | diagID = diag::err_uncasted_call_of_unknown_any; |
| 17619 | loc = msg->getSelectorStartLoc(); |
| 17620 | d = msg->getMethodDecl(); |
| 17621 | if (!d) { |
| 17622 | S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) |
| 17623 | << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() |
| 17624 | << orig->getSourceRange(); |
| 17625 | return ExprError(); |
| 17626 | } |
| 17627 | } else { |
| 17628 | S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) |
| 17629 | << E->getSourceRange(); |
| 17630 | return ExprError(); |
| 17631 | } |
| 17632 | |
| 17633 | S.Diag(loc, diagID) << d << orig->getSourceRange(); |
| 17634 | |
| 17635 | // Never recoverable. |
| 17636 | return ExprError(); |
| 17637 | } |
| 17638 | |
| 17639 | /// Check for operands with placeholder types and complain if found. |
| 17640 | /// Returns ExprError() if there was an error and no recovery was possible. |
| 17641 | ExprResult Sema::CheckPlaceholderExpr(Expr *E) { |
| 17642 | if (!getLangOpts().CPlusPlus) { |
| 17643 | // C cannot handle TypoExpr nodes on either side of a binop because it |
| 17644 | // doesn't handle dependent types properly, so make sure any TypoExprs have |
| 17645 | // been dealt with before checking the operands. |
| 17646 | ExprResult Result = CorrectDelayedTyposInExpr(E); |
| 17647 | if (!Result.isUsable()) return ExprError(); |
| 17648 | E = Result.get(); |
| 17649 | } |
| 17650 | |
| 17651 | const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); |
| 17652 | if (!placeholderType) return E; |
| 17653 | |
| 17654 | switch (placeholderType->getKind()) { |
| 17655 | |
| 17656 | // Overloaded expressions. |
| 17657 | case BuiltinType::Overload: { |
| 17658 | // Try to resolve a single function template specialization. |
| 17659 | // This is obligatory. |
| 17660 | ExprResult Result = E; |
| 17661 | if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) |
| 17662 | return Result; |
| 17663 | |
| 17664 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization |
| 17665 | // leaves Result unchanged on failure. |
| 17666 | Result = E; |
| 17667 | if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) |
| 17668 | return Result; |
| 17669 | |
| 17670 | // If that failed, try to recover with a call. |
| 17671 | tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), |
| 17672 | /*complain*/ true); |
| 17673 | return Result; |
| 17674 | } |
| 17675 | |
| 17676 | // Bound member functions. |
| 17677 | case BuiltinType::BoundMember: { |
| 17678 | ExprResult result = E; |
| 17679 | const Expr *BME = E->IgnoreParens(); |
| 17680 | PartialDiagnostic PD = PDiag(diag::err_bound_member_function); |
| 17681 | // Try to give a nicer diagnostic if it is a bound member that we recognize. |
| 17682 | if (isa<CXXPseudoDestructorExpr>(BME)) { |
| 17683 | PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; |
| 17684 | } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { |
| 17685 | if (ME->getMemberNameInfo().getName().getNameKind() == |
| 17686 | DeclarationName::CXXDestructorName) |
| 17687 | PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; |
| 17688 | } |
| 17689 | tryToRecoverWithCall(result, PD, |
| 17690 | /*complain*/ true); |
| 17691 | return result; |
| 17692 | } |
| 17693 | |
| 17694 | // ARC unbridged casts. |
| 17695 | case BuiltinType::ARCUnbridgedCast: { |
| 17696 | Expr *realCast = stripARCUnbridgedCast(E); |
| 17697 | diagnoseARCUnbridgedCast(realCast); |
| 17698 | return realCast; |
| 17699 | } |
| 17700 | |
| 17701 | // Expressions of unknown type. |
| 17702 | case BuiltinType::UnknownAny: |
| 17703 | return diagnoseUnknownAnyExpr(*this, E); |
| 17704 | |
| 17705 | // Pseudo-objects. |
| 17706 | case BuiltinType::PseudoObject: |
| 17707 | return checkPseudoObjectRValue(E); |
| 17708 | |
| 17709 | case BuiltinType::BuiltinFn: { |
| 17710 | // Accept __noop without parens by implicitly converting it to a call expr. |
| 17711 | auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); |
| 17712 | if (DRE) { |
| 17713 | auto *FD = cast<FunctionDecl>(DRE->getDecl()); |
| 17714 | if (FD->getBuiltinID() == Builtin::BI__noop) { |
| 17715 | E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), |
| 17716 | CK_BuiltinFnToFnPtr) |
| 17717 | .get(); |
| 17718 | return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, |
| 17719 | VK_RValue, SourceLocation()); |
| 17720 | } |
| 17721 | } |
| 17722 | |
| 17723 | Diag(E->getBeginLoc(), diag::err_builtin_fn_use); |
| 17724 | return ExprError(); |
| 17725 | } |
| 17726 | |
| 17727 | // Expressions of unknown type. |
| 17728 | case BuiltinType::OMPArraySection: |
| 17729 | Diag(E->getBeginLoc(), diag::err_omp_array_section_use); |
| 17730 | return ExprError(); |
| 17731 | |
| 17732 | // Everything else should be impossible. |
| 17733 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
| 17734 | case BuiltinType::Id: |
| 17735 | #include "clang/Basic/OpenCLImageTypes.def" |
| 17736 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
| 17737 | case BuiltinType::Id: |
| 17738 | #include "clang/Basic/OpenCLExtensionTypes.def" |
| 17739 | #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: |
| 17740 | #define PLACEHOLDER_TYPE(Id, SingletonId) |
| 17741 | #include "clang/AST/BuiltinTypes.def" |
| 17742 | break; |
| 17743 | } |
| 17744 | |
| 17745 | llvm_unreachable("invalid placeholder type!" ); |
| 17746 | } |
| 17747 | |
| 17748 | bool Sema::CheckCaseExpression(Expr *E) { |
| 17749 | if (E->isTypeDependent()) |
| 17750 | return true; |
| 17751 | if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) |
| 17752 | return E->getType()->isIntegralOrEnumerationType(); |
| 17753 | return false; |
| 17754 | } |
| 17755 | |
| 17756 | /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. |
| 17757 | ExprResult |
| 17758 | Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { |
| 17759 | assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && |
| 17760 | "Unknown Objective-C Boolean value!" ); |
| 17761 | QualType BoolT = Context.ObjCBuiltinBoolTy; |
| 17762 | if (!Context.getBOOLDecl()) { |
| 17763 | LookupResult Result(*this, &Context.Idents.get("BOOL" ), OpLoc, |
| 17764 | Sema::LookupOrdinaryName); |
| 17765 | if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { |
| 17766 | NamedDecl *ND = Result.getFoundDecl(); |
| 17767 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) |
| 17768 | Context.setBOOLDecl(TD); |
| 17769 | } |
| 17770 | } |
| 17771 | if (Context.getBOOLDecl()) |
| 17772 | BoolT = Context.getBOOLType(); |
| 17773 | return new (Context) |
| 17774 | ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); |
| 17775 | } |
| 17776 | |
| 17777 | ExprResult Sema::ActOnObjCAvailabilityCheckExpr( |
| 17778 | llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, |
| 17779 | SourceLocation RParen) { |
| 17780 | |
| 17781 | StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); |
| 17782 | |
| 17783 | auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { |
| 17784 | return Spec.getPlatform() == Platform; |
| 17785 | }); |
| 17786 | |
| 17787 | VersionTuple Version; |
| 17788 | if (Spec != AvailSpecs.end()) |
| 17789 | Version = Spec->getVersion(); |
| 17790 | |
| 17791 | // The use of `@available` in the enclosing function should be analyzed to |
| 17792 | // warn when it's used inappropriately (i.e. not if(@available)). |
| 17793 | if (getCurFunctionOrMethodDecl()) |
| 17794 | getEnclosingFunction()->HasPotentialAvailabilityViolations = true; |
| 17795 | else if (getCurBlock() || getCurLambda()) |
| 17796 | getCurFunction()->HasPotentialAvailabilityViolations = true; |
| 17797 | |
| 17798 | return new (Context) |
| 17799 | ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); |
| 17800 | } |
| 17801 | |